axios的使用说明
时间: 2024-05-13 09:11:55 浏览: 9
Axios是一个基于Promise的HTTP客户端,可以在浏览器和Node.js中使用,用于发送HTTP请求并处理响应。它具有以下特点:
1. 可以拦截请求和响应
2. 自动转换JSON数据
3. 可以取消请求
4. 支持Promise API
5. 提供了一些方便的方法来处理请求和响应,例如拦截器、并发请求、身份验证等
下面是axios的使用示例:
1. 安装axios:
```js
npm install axios
```
2. 发送GET请求:
```js
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
3. 发送POST请求:
```js
axios.post('/user', {
firstName: 'John',
lastName: 'Doe'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
4. 发送并发请求:
```js
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
```
5. 配置axios实例:
```js
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
instance.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```