这是我参与更文挑战的第15天,活动详情查看: 更文挑战
介绍
-
什么是 axios?
-
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
-
参考:axios中文网
特性
- 从浏览器中创建XMLHttpRequests
- 从 node.js 创建http请求
- 支持PromiseAPI
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御XSRF
安装
使用 npm:
$ npm install axios
复制代码
使用 bower:
$ bower install axios
复制代码
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
复制代码
案例
执行GET请求
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
复制代码
执行POST请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
复制代码
执行多个并发请求
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) {
// 两个请求现在都执行完成
}));
// 或者
axios.all([
axios.post(url),
axios.get(url, params)
]).then(axios.spread((res1, res2) => {
console.log(res1);
console.log(res2)
}))
复制代码
拦截器
应用场景:
1:每个请求都带上的参数,比如token,时间戳等。
2:对返回的状态进行判断,比如token是否过期。
在请求或响应被 then 或 catch 处理前拦截它们。
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
复制代码
如果你想在稍后移除拦截器,可以这样:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
复制代码
可以为自定义 axios 实例添加拦截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
复制代码
前往我的个人github查看拦截器的举例以及axios封装管理,位于以下文件夹,如图:
github.com/zchaoGe/Ele…
请求数据格式
1、请求数据格式为 application/x-www-form-urlencoded
axios设置:headers
和 transformRequest
axios({
url: 'xxx',
method: 'GET',
headers: {
"Content-Type": 'application/x-www-form-urlencoded'
},
transformRequest: [function (data) {
let ret = '';
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
}
return ret
}],
params: data
}).then(res => {
// something code
}).catch(() => {
// something code
})
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END