1.前言
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,之所以前端流行是因为它可以用在浏览器和 node.js 中,axios在浏览器端使用XMLHttpRequest对象发送ajax请求,在node环境使用http对象发送ajax请求,并且符合现在前端MVVM的开发模式,react/vue 官方都推荐使用 它,可以说是前端必备的知识了!
2.项目引入
1. 项目中安装
npm install axios vue-axios --save -dev
2. 项目中引入
import Axios from "axios"
import VueAxios from "vue-axios"
Vue.use(VueAxios,Axios);
3. 项目中使用this.$http发送请求
created() {
this.$http.get("xxxx/xxxx").then((response) => {
// ...
},(error)=>{
// ....
});
},
3.语法
1.可以通过向 axios 传递相关配置来创建请求!
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'zhang',
lastName: 'san'
}
});
配置很多,我列下比较常用的,比较基础的会写上注释,有些不好理解的我会举例说明
1. url: url 是用于请求的服务器 URL。
2.method: method是创建请求时使用的方法。
3. baseURL:baseURL 将自动加在 url前面,除非url是一个绝对 URL。
4. params:params是即将与请求一起发送的 URL 参数(拼接到url后面)。
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
params:{
a:1,
b:2
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
5. data:作为请求主体被发送的数据,只适用于这些请求方法 PUT, POST, 和 PATCH。
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
data:{
x: 1,
y: 2
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
6. transformRequest:允许在向服务器发送前,修改请求数据, 只能用在 PUT, POST 和 PATCH 这几个请求方法,后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream。下面演示下把请求主体被发送的数据变成 URL 参数的格式
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
transformRequest: [
function (data, headers) {
// qs库编码数据
const qs = require('qs');
return qs.stringify(data);
}
],
data:{
x: 1,
y: 2
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
7. transformResponse:在传递给 then/catch 前,允许修改响应数据。
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
transformResponse: [
function (data, headers) {
// 默认是string类型,转成对象并添加name属性
data = JSON.parse(data);
data.name="zhangsan";
console.log(data);
return data;
}
]
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
8. responseType: 表示服务器响应的数据类型,默认是json,具体类型可以是 arraybuffer, blob, document, json, text, stream。 不过text有个bug(我觉得是bug,应该返回后的是string类型,但是还是json对象)。
//axios 请求
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
responseType: "text",
})
.then(function (response) {
console.log(response.data, "axios返回类型:" + typeof response.data);
})
.catch(function (error) {
console.log(error);
});
//原生xhr请求
let xhr = new XMLHttpRequest();
xhr.open(
"post",
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena/post/test",
true
);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.responseType = "text";
xhr.onload = function () {
console.log(
this.response,
"原生js返回类型:" + typeof this.response
);
};
xhr.send();
//jquery ajax请求
ajax.post({
url: "https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena/post/test",
method: "post",
dataType: "text",
success: function (data) {
console.log(data, "原生ajax返回类型:" + typeof data);
},
});
}
原生的js和jquery的ajax请求都是正常返回string类型,但是只是axios返回的还是json,我想是个bug吧,如果想要字符串,我要你可能还需要自己手动转下!
9. headers: 是即将被发送的自定义请求头,比如需要验证的token。
10. paramsSerializer:是一个负责 params序列化的函数。如果是对象,可能你不需要序列化,会自动转成(key1=value1&key2=value2)的形式,但是如果是数组,将一个数组作为一个请求参数传递,要么axios直接抛出连接异常,要么后端接口接收不到匹配的参数。所以这时候你需要用上这个序列化函数,可以引入一个序列化的库qs,这里有4种序列化形式!具体需要什么要看需求!
//形式1:
qs.stringify({ids: [1, 2, 3]}, { indices: false })
//ids=1&ids=2&id=3
//形式2:
qs.stringify({ids: [1, 2, 3]}, {arrayFormat: ‘indices‘})
// ids[0]=1&aids1]=2&ids[2]=3
//形式3:
qs.stringify({ids: [1, 2, 3]}, {arrayFormat: ‘brackets‘})
//ids[]=1&ids[]=2&ids[]=3
//形式4:
qs.stringify({ids: [1, 2, 3]}, {arrayFormat: ‘repeat‘})
// ids=1&ids=2&id=3
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
params:{
a:[1,2,3]
},
paramsSerializer:params=> {
return qs.stringify(params, { arrayFormat: "repeat" });
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
11. timeout: 指定请求超时的毫秒数,如果请求时间超过设置的时间,请求将被中断。好比一个请求比如正常需要2000毫秒,但是你设置timeout时间为1000毫秒,那么怎么请求都会是失败的!这里为了演示,我设置5毫秒。
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
timeout:5
}).then(function (response) {
console.log(response);
}).catch(function (error) {
//Error: timeout of 5ms exceeded
console.log(error);
});
12. validateStatus:定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 validateStatus返回 true,promise 将被 resolve; 返回false,promise 将被 rejecte,换句话说就是可以自己定义状态码!
this.$http({
url: "/post/test",
baseURL:
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena",
method: "post",
validateStatus: function (status) {
return status >= 200 && status < 300 // default
},
}).then(function (response) {
console.log(response);
}).catch(function (error) {
//Error: timeout of 5ms exceeded
console.log(error);
});
2.为方便起见,为所有支持的请求方法提供了别名,可以通过别名来创建请求!
1. axios.get(url[, config])
2. axios.delete(url[, config])
3. axios.head(url[, config])
4. axios.options(url[, config])
5. axios.post(url[, data[, config]])
6. axios.put(url[, data[, config]])
7. axios.patch(url[, data[, config]])
config的常用配置上面都已经说过了,可能有很多人看不懂[ ,]的意思,顺便说下吧![ ]代表是可选参数,[ ]里面的逗号是参数的分割,就拿axios.get(url[, config])来说吧,config是可选参数,如果有config参数就是axios.get(url, config),如果没有config参数就是axios.get(url)!
4.并发请求
4.1 axios.all
let getPromise = this.$http.get(
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena/get/test"
),
postPromise = this.$http.post(
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena/post/test"
);
this.$http.all([getPromise, postPromise]).then((response) => {
console.log(response);
});
返回的是一个数组,那么要拿到结果就需要循环它了,并且返回的结果顺序也不一定是你前面写的参数的顺序(谁先执行完,哪个就在第一个位置),那么axios.spread正好就可以解决这个问题!
4.2 axios.spread
let getPromise = this.$http.get(
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena/get/test"
),
postPromise = this.$http.post(
"https://www.fastmock.site/mock/257d9fdebd0b1dd887acd6ec80db8ade/cena/post/test"
);
this.$http.all([getPromise, postPromise]).then(this.$http.spread((getPromise,postPromise) => {
console.log(getPromise,postPromise);
}));
返回的是多个对象,并且spread回调参数和前面all写的参数的是一一对应的!