npm安装:
1. npm i/install axios --save-dev/-D
也可以引入网络链接通过script标签
在config/index.js里面配置代理:
proxyTable:{
"/api":{
target:"http://...." //目标地址
changeOrigin:true,
pathRewrite:{
"^/api":"" //把理由中的api开头的路由置空
}
}
}
全局配置axios
import axios from "axios";
Vue.prototype.$http = axios;
<!--使用-->
this.$http({
url:"/api/...",
method:"post" //默认是get,
data:{}
})
局部配置
局部配置和全局配置用法一样,不过局部用法就得在每一个要使用的组件中都得引入
可以通过向 axios 传递相关配置来创建请求
axios(config)
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[, config])
// 发送 GET 请求(默认的方法)
axios('/user/12345');
常用使用方法
执行 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) {
// 两个请求现在都执行完成
}));
get和post提交的区别
- get的参数可以拼接到链接地址之后也可以使用params进行数据提交
- post需要使用data进行数据提交
- form数据提交
- new formDate()
- 把需要提交的表单数据用实例化formDate进行append追加
- 如果数据是个对象,可以遍历对象
- for in 是遍历对象哦
- 图片数据获取可以用ref
- this.refs.ref名.files进行信息获取
axios可以通过create创建一个实例
let instance = axios.create();
- intercptors属性是拦截器(请求与相应拦截器)
- intercptors.(request || respones).use
- axios.defaults是默认配置
- axios.default.header
- axios.default.baseurl