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
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/905044329734bf281720e8ed9a563b33.png)
二、prototype装载
import request from "@/utils/request";
Vue.prototype.request=request
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6f28a60addc00a6822cbc84bc039d6fa.png)
三、使用
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
})
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/93f0c6a9457c3b2fe71267e26ec3fe73.png)