axios ajax库 (vue+axios react+axios angular+axios)
axios 是一个 封装好的 第三方ajax请求的库
特点:支持restfulapi
支持promise 解决回到地狱
支持ajax请求拦截
vue-resource 停止维护了 ,官网不推荐使用
get请求:
axios.get('url?params1=v¶ms2=值2').then().catch()
axios.get(url,{
params:{
key1:v1,
key2:v2
}
})
post请求:
axios.post(url,{
key1:v1,
key2:v2
}).then().catch()
注意:axios 中 默认 是以 json的形式发送数据 不是以
application/x-www-form-urlencoded "名字=值&名字2=值2"
json
{
key:v
}
所以 你在和后端交互时,后端如果没有配置 接收post json格式,会导致后端接收不到数据
如何解决?
1,设置axios
request-headers content-type默认值 "application/json"
content-type:"application/x-www-form-urlencoded"
2,使用qs 库
npm i qs -S
import qs from 'qs'
qs.stringify({
a:10,
b:20
})
结果: "a=10&b=20"
qs.parse("a=10&b=20");
结果:
{
a:10,
b:20
}
直接使用
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then().catch()
创建一个实例来使用
const http = axios.create({
baseURL: 'http://localhost:3000',
timeout: 8000,
headers: {}
});
使用时,同axios
http.get()
http.post()
axios拦截器: 用于做全局的axios封装(结合实例来使用)
axios.interceptors.request.use(function (config) {
// 可以拦截请求,在请求发送之前做啥都行
config.data = qs.stringify(data)
return config;
}, function (error) {
// 当请求错误之后会在这里拦截
return Promise.reject(error);
});
// Add a 相应拦截 interceptor
axios.interceptors.response.use(function (response) {
// response 是服务端相应的数据 成功返回会在这里拦截
return response;
}, function (error) {
// 服务器返回出错,会在这里进行拦截
return Promise.reject(error);
});
https://www.jianshu.com/p/7387a28a7e6f 实战中 vue 封装axios