vue+axios(vueaxios封装)

Vue axios

简介:

Vue axios 是一个基于 Promise 的 HTTP 请求库,可以用来发送 HTTP 请求并处理响应数据。它是基于 promise 的技术,可以在浏览器和 Node.js 中使用。

多级标题:

一、安装

二、基本用法

三、发送GET请求

四、发送POST请求

五、拦截器

六、错误处理

一、安装:

要使用 Vue axios,首先需要安装它。可以通过 npm 或 yarn 进行安装。

```

npm install axios

```

```

yarn add axios

```

二、基本用法:

在应用程序中使用 Vue axios 需要先引入它:

```

import axios from 'axios';

```

然后,可以通过创建一个 axios 实例来发送请求:

```

const instance = axios.create({

baseURL: 'https://api.example.com',

timeout: 5000

});

```

其中,baseURL 是请求的基本 URL,timeout 是请求超时时间。

三、发送GET请求:

可以使用 axios 的 get 方法发送 GET 请求:

```

instance.get('/users')

.then(response => {

// 处理响应数据

})

.catch(error => {

// 处理错误

});

```

四、发送POST请求:

可以使用 axios 的 post 方法发送 POST 请求:

```

instance.post('/users', {name: 'John', age: 30})

.then(response => {

// 处理响应数据

})

.catch(error => {

// 处理错误

});

```

五、拦截器:

可以使用 axios 的拦截器来在请求或响应被 then 或 catch 处理前拦截它们。

例如,可以在请求被发送之前,添加一个拦截器来在请求头中添加 token:

```

instance.interceptors.request.use(config => {

config.headers.Authorization = 'Bearer ' + getToken();

return config;

}, error => {

return Promise.reject(error);

});

```

六、错误处理:

使用 axios 发送请求时,可能会遇到一些错误。可以通过 catch 语句来处理这些错误:

```

instance.get('/users')

.then(response => {

// 处理响应数据

})

.catch(error => {

if (error.response) {

// 请求已发出,响应的状态码不是 2xx

console.log(error.response.data);

console.log(error.response.status);

console.log(error.response.headers);

} else if (error.request) {

// 请求已发出,但没有收到响应

console.log(error.request);

} else {

// 发送请求时出错

console.log('Error', error.message);

}

console.log(error.config);

});

```

以上就是 Vue axios 的基本用法和一些常见功能的介绍。通过使用 Vue axios,我们可以轻松发送 HTTP 请求并处理响应数据。

标签列表