一、什么是axios?
axios 是基于 Promise 用于浏览器和 nodejs 的 HTTP 客户端。
1.从浏览器创建 XMLHttpRequest
2.支持 Promise API
3.拦截请求和响应
4.转换请求和响应数据
5.取消请求
6.自动转换 JSON 数据
7.客户端支持防止 CSRF/XSRF => CSRF(Cross-site request forgery跨站请求伪造,也就是钓鱼。详细解释请看链接:https://www.cnblogs.com/Erik_Xu/p/5481441.html)
二、axios常见用法
1.执行单个请求:
没有指定 method,请求将默认使用 get 方法
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2.执行多个请求:
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) {
// 两个请求现在都执行完成
}));
3.自定义创建实例:
可以使用自定义配置新建一个 axios 实例
axios.create([config])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
网友评论