文章目录
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
基本用法
安装
使用npm安装:npm install axios
使用 bower安装:bower install axios
使用yarn安装axios:yarn install axios
使用 cdn安装:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
1.vue.use方法
在 main.js
中引入 axios
import axios from 'axios'
import Axios from 'vue-axios'
Vue.use(Axios,axios);
在组件文件中的methods里去使用axios
getNewsList(){
this.axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
}
2.axios 改写为 Vue 的原型属性
在 main.js
中引入 axios
import axios from 'axios'
Vue.prototype.$ajax= axios
在组件中使用:
this.$ajax.get('api/getNewsList')
.then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
常用的配置项初始化
// 常规配置项
axios.defaults.baseURL = 'https://127.0.0.1:9999'; // 请求服务器具体的地址
axios.defaults.withCredentials =true; // 在跨域中允许携带凭证
axios.defaults.header['Content-Type'] = 'application/x-www-form-urlencoded';// 声明传给服务器的数据,通过请求传给服务器的数据application/x-www-form-urlencoded格式
axios.defaults.headers.common["token"] = token; // 携带token请求头
// 请求拦截器:当我们通过porps请求向服务器发请求的时候,能拦截到请求主体信息,然后把请求主体传递进来的json格式的对象,变成urlencoded 某某某等于&某某某格式发送给服务器
axios.defaults.transformRequest = function (data) {
if (data) return data;
let result = ``;
for (let attr in data) {2
if(!data.hasOwnProperty(attr)) break;
result += `&${attr}=${data[attr]}`;
}
return result.substring(1);
};
// 响应服务器:接受服务器返回的结果,把返回的结果,因为它的anshuosi从服务器获得的结果response对象当中包含了很多信息,既有响应头也有相应主体的信息,xx配置信息。
// 现在只拿到data,如果有错误就抛出错误的Promise,
axios.interceptor.response.use(function onFultfilled(response) {
// 成功走这个
return response.data;
}, function onRejected(reason) {
// 失败走这个
return Promise.reject(reason);
});
// 验证什么时候成功失败,用正则检验,自定义成功失败,主要以http状态码
axios.dafaults.validateStatus = function (status) {
// http状态码,2或者3开头的都是成功,默认只有2开头的才能成功
return /^(2\3)\d{2}$/.test(status);
axios请求方法
- post:向指定资源提交数据(例如表单提交或文件上传)
- get:获取数据,请求指定的信息,返回实体对象
- put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
- patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
- delete:请求服务器删除指定的数据
get请求:
get请求:方式一:
axios({
// 默认请求方式为get
method: 'get',
url: 'api',
// 传递参数
params: {
key: value
},
// 设置请求头信息
headers: {
key: value
}
responseType: 'json'
}).then(response => {
// 请求成功
let res = response.data;
console.log(res);
}).catch(error => {
// 请求失败,
console.log(error);
});
get请求:方式二
axios.get("api", {
// 传递参数
params: {
key: value
},
// 设置请求头信息,可以传递空值
headers: {
key: value
}
}).then(response => {
// 请求成功
let res = response.data;
console.log(res);
}).catch(error => {
// 请求失败,
console.log(error);
});
post请求
post请求:方式一
// 注:post请求方法有的要求参数格式为formdata格式,此时需要借助 Qs.stringify()方法将对象转换为字符串
let obj = qs.stringify({
key: value
});
axios({
method: 'post',
url: 'api',
// 传递参数
data: obj,
// 设置请求头信息
headers: {
key: value
}
responseType: 'json'
}).then(response => {
// 请求成功
let res = response.data;
console.log(res);
}).catch(error => {
// 请求失败,
console.log(error);
});
post请求:方式二
let data = {
key: value
},
headers = {
USERID: "",
TOKEN: ""
};
// 若无headers信息时,可传空对象占用参数位置
axios.post("api", qs.stringify(data), {
headers
}
}).then(response => {
// 请求成功
let res = response.data;
console.log(res);
}).catch(error => {
// 请求失败,
console.log(error);
});
put和patch请求
//put请求
this.$axios.put('/url',{
id:1
}).then(res=>{
console.log(res.data);
})
//patch请求
this.$axios.patch('/url',{
id:1
}).then(res=>{
console.log(res.data);
})
delete请求
//参数以明文形式提交
this.$axios.delete('/url',{
params: {
id:1
}
}).then(res=>{
console.log(res.data);
})
//参数以封装对象的形式提交
this.$axios.delete('/url',{
data: {
id:1
}
}).then(res=>{
console.log(res.data);
})
//方法二
axios({
method: 'delete',
url: '/url',
params: { id:1 }, //以明文方式提交参数
data: { id:1 } //以封装对象方式提交参数
}).then(res=>{
console.log(res.data);
})
并发请求(同时进行多个请求,并统一处理返回值)
this.$axios.all([
this.$axios.get('/goods.json'),
this.$axios.get('/classify.json')
]).then(
this.$axios.spread((goodsRes,classifyRes)=>{
console.log(goodsRes.data);
console.log(classifyRes.data);
})
)
axios实例
创建axios实例
let instance = this.$axios.create({
baseURL: 'http://localhost:9090',
timeout: 2000
})
instance.get('/goods.json').then(res=>{
console.log(res.data);
})
可以同时创建多个axios实例。
axios实例常用配置:
- baseURL 请求的域名,基本地址,类型:String
- timeout 请求超时时长,单位ms,类型:Number
- url 请求路径,类型:String
- method 请求方法,类型:String
- headers 设置请求头,类型:Object
- params 请求参数,将参数拼接在URL上,类型:Object
- data 请求参数,将参数放到请求体中,类型:Object
axios全局配置
//配置全局的超时时长
this.$axios.defaults.timeout = 2000;
//配置全局的基本URL
this.$axios.defaults.baseURL = 'http://localhost:8080';
axios实例配置
let instance = this.$axios.create();
instance.defaults.timeout = 3000;
axios请求配置
this.$axios.get('/goods.json',{
timeout: 3000
}).then()
以上配置的优先级为:
请求配置 > 实例配置 > 全局配置
拦截器(在请求或响应被处理前拦截它们)
请求拦截器
this.$axios.interceptors.request.use(config=>{
// 发生请求前的处理
return config
},err=>{
// 请求错误处理
return Promise.reject(err);
})
//或者用axios实例创建拦截器
let instance = this.$axios.create();
instance.interceptors.request.use(config=>{
return config
})
响应拦截器
this.$axios.interceptors.response.use(res=>{
//请求成功对响应数据做处理
return res //该返回对象会传到请求方法的响应对象中
},err=>{
// 响应错误处理
return Promise.reject(err);
})
取消拦截
let instance = this.$axios.interceptors.request.use(config=>{
config.headers = {
token: ''
}
return config
})
//取消拦截
this.$axios.interceptors.request.eject(instance);
错误处理
this.$axios.get('/url').then(res={
}).catch(err=>{
//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
console.log(err);
})
取消请求(主要用于取消正在进行的http请求。)
let source = this.$axios.CancelToken.source();
this.$axios.get('/goods.json',{
cancelToken: source
}).then(res=>{
console.log(res)
}).catch(err=>{
//取消请求后会执行该方法
console.log(err)
})
//取消请求,参数可选,该参数信息会发送到请求的catch中
source.cancel('取消后的信息');