经常使用到vue,axios封装也是比较常见的,可优化代码可读性 ,代码如下:
import axios from "axios"
const baseURL = "https://...."
const distance = axios.create({
baseURL:baseURL
});
import { Message } from ‘element-ui‘;
function post(url, params) {
return new Promise((resolve, reject) => {
distance.post(url, params)
.then(res => {
resolve(res);
})
.catch(err =>{
reject(err)
})
});
}
function get(url,param){
return new Promise((resolve ,reject) => {
distance.get(url,param)
.then(res=>{
resolve(res);
})
.catch(err =>{
reject(err);
})
})
}
function put(url,param){
return new Promise((resolve ,reject) => {
distance.put(url,param)
.then(res=>{
resolve(res);
})
.catch(err =>{
reject(err);
})
})
}
function del(url){
return new Promise((resolve ,reject) => {
distance.delete(url)
.then(res=>{
resolve(res);
})
.catch(err =>{
reject(err);
})
})
}
//请求拦截
distance.interceptors.request.use(config =>{
let token = sessionStorage.getItem("token");
if(token !== ‘‘){
let tmp = token.substr(1,token.length-1);
config.headers["Authority-Token"] = tmp.substr(0,token.length-2);
}
return config;
})
//响应拦截
distance.interceptors.response.use(config=>{
return config;
}, err => {
console.log(err)
if(err.response.status == 400 || err.response.status_code == 400){
Message.error(err.response.data.message);
}
if(err.response.data.message == "token已过期,请重新登录"){
sessionStorage.setItem("token","")
sessionStorage.setItem("user","")
window.location.reload();
}
return err;
})
export const Login = function (user,pwd) {
return post("/login",{user,pwd});
}