引入方式
使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
或
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
使用npm方式
$ npm install axios
使用bower方式
$ bower install axios
使用yarn方式
$ yarn add axios
使用方式
Vue.axios.get(外部api).then((response) => {
console.log(response.data)
})
this.axios.get(外部api).then((response) => {
console.log(response.data)
})
this.$http.get(外部api).then((response) => {
console.log(response.data)
})
GET传递参数方式
可直接加入到mount等script中执行
// 直接在 URL 上添加参数 id=1
axios.get('/user?id=1')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 设置参数:
axios.get('/user', {
params: {
id: 1
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
POST传递参数方式
axios.post('/userpost', {
name: 'jack', // 参数 name
cname: 'rose' // 参数 cname
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多个并发请求
function getUser1() {
return axios.get('/user/1');
}
function getUser2() {
return axios.get('/username/2/permissions');
}
axios.all([getUser1(), getUser2()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
axios响应结构
{
// `data` 由服务器提供的响应
data: {},
// `status` HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: "OK",
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {}
}
使用then接收时可以如下获取:
axios.get("/username/1")
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
axios默认配置
指定被用于各个请求的默认配置。
axios.defaults.baseURL = 'https://api.yvyv.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
当需要改变默认配置时,可自定义创建如下:
// 创建实例时设置默认值
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// 在实例已创建后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
默认配置的采用存在优先顺序,具体顺序如下:
在 lib/defaults.js 找到的库的默认值
实例的 defaults 属性
请求的 config 参数
实际使用时,后面的优先级高于前面的
例子:
// 使用由库提供的配置的默认值创建实例
// 此时超时配置的默认值是 `0`
var axiosInstance= axios.create();
// 覆写库的超时默认值
// 现在,在超时前,所有请求都会等待 2.5 秒
axiosInstance.defaults.timeout = 2500;
// 为已知需要花费很长时间的请求覆写超时设置
axiosInstance.get('/longRequest', {
timeout: 5000
});
拦截器,在axios请求发出或者响应前做处理
// 添加请求拦截器
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);
});
不需要拦截器,主动撤销拦截器时
var axiosIcpt= axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(axiosIcpt);