axios二次封装
一、request.js
import axios from 'axios'
import router from "@/router";
const request = axios.create({
baseURL: 'http://localhost:9090',
timeout: 5000
})
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null
if (user) {
config.headers['token'] = user.token;
}
return config
}, error => {
return Promise.reject(error)
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
if (res.code === '401') {
router.push("/login")
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request
二、prototype装载
import request from "@/utils/request";
Vue.prototype.request=request
三、使用
this.request.get("/user/page", {
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
username: this.username,
email: this.email,
address: this.address,
}
}).then(res => {
this.tableData = res.data.records
this.total = res.data.total
})