Axios基本用法
一、Axios特点
二、基本使用
- 安装
cnpm install axios -S
- get为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- get上面的请求可以这样做
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);
});
- 用promise执行多个并发请求
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) {
// 两个请求现在都执行完成
}));
- 综合写法
axios({
mehtods:"get/post"
url:""
data:"post请求传递的数据"
params:"get请求传递的数据"
})
三、封装Axios请求
- require.js
export default (options) => {
return new Promise((resolve, reject) => {
$.ajax({
type: options.method || "GET",
url: options.url,
data: options.data,
headers: options.headers || {},
success: function (data) {
resolve(data);
},
error: function (err) {
reject(err)
}
})
})
}
四、常用的配置项
url用于请求的服务器 URL
创建请求时使用的方法method
baseUrl
- headers即将被发送的自定义请求头
- timeout
- withCredentials
- axios.create()创建自定义配置项
- 可以通过全区的axios重新配置默认值
- 拦截器
五、Axios的二次封装
- 安装qs(不同于querystring)
cnpm install qs -S
import axios from "axios";
const server = axios.create({
timeout:5000,
//baseUrl:"",
withCredentials:true
})
//请求的拦截
server.interceptors.request.use((config)=>{
if(config.method == "get"){
config.params = {...config.data};
}
return config;
//config.headers["content-type"] = "application/json"
},(err)=>{
return Promise.reject(err)
})
//响应的拦截
server.interceptors.response.use((res)=>{
if(res.status == 200){
return res.data;
}
},(err)=>{
return Promise.reject(err)
})
export default server;