axios
基于promise用于浏览器和node.js的http客户端
特点
- 支持浏览器和node.js
- 支持promise
- 能拦截请求和响应
- 能转换请求和响应数据
- 能取消请求
- 自动转换JSON数据
- 浏览器端支持防止CSRF(跨站请求伪造)
第一步:安装
在要使用的项目中使用cmd进入命令行工具,输入下面指令:
$ npm install axios
第二步:配置
(全局)在项目main.js文件中
import axios from "axios"
Vue.prototype.axios = axios
(组件)在要使用的组件中
import axios from "axios"
这里要注意的是全局引入的情况下使用时是 this.$axios
之后就可以使用axios了,下面是例子
发起一个GET请求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
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) {
// Both requests are now complete
}));
配置反向代理
在工程目录config文件夹中index.js文件中添加
'/api':{
target:"http://localhost:8080", //第三方接口
changeOrigin: true, //跨域
pathRewrite: {
'^/api': '/static/mock' //这里根据需要可以修改地址,我这里配置的是本地存放json的文件夹
}
}