vue2+axios请求拦截
依赖项
“vue”: “^2.6.11”
“axios”: “^0.21.0”
“element-ui”: “^2.13.2”(做弹窗提示,可以不用)
http.js
// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import {
Loading,
Message
} from 'element-ui'
import router from '../../router/index'
// 超时时间
axios.defaults.timeout = 5000
// http请求拦截器
var loadinginstace
axios.interceptors.request.use(config => {
// element ui Loading方法
loadinginstace = Loading.service({
fullscreen: true
})
return config
}, error => {
loadinginstace.close()
Message.error({
message: '加载超时'
})
return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => { // 响应成功关闭loading
loadinginstace.close()
const code = data.data.code;
if (code == 401) {
Message.closeAll()
router.push('/')
sessionStorage.removeItem('author')
return data;
}
return data;
}, error => {
loadinginstace.close()
if (error.toString().indexOf('timeout')) {
error = '请求超时!'
}
return Promise.reject(error)
})
export default axios
vue2+axios设置请求头
依赖项
“vue”: “^2.6.11”
“axios”: “^0.21.0”
“element-ui”: “^2.13.2”(做弹窗提示,可以不用)
http.js
// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
if (sessionStorage.getItem("author")) {
axios.defaults.headers.common["Authorization"] = sessionStorage.getItem("author");
}
// 超时时间
axios.defaults.timeout = 5000
axios.defaults.withCredentials = true
export default axios
获取并设置请求头
api.js
import axios from '../assets/js/http'
const IP = "http://xxxx:xx" // test
/**
* 登录
* @returns
*/
export function rpc_login(
username,
password
) {
return axios.post(IP + "/auth/login", {
username,
password,
}, {
transformRequest: [function (data, headers) {
if (headers.common.Authorization) {
delete headers.common.Authorization;
}
return JSON.stringify(data);
}],
headers: {
"Content-Type": "application/json"
}
})
}
a.vue
rpc_login(this.username, this.password)
.then((res) => {
if (res.data.code == "200") {
axios.defaults.headers.common["Authorization"] = res.data.data;
sessionStorage.setItem("author", res.data.data);
this.$router.push("/home");
} else {
this.$message.error(res.data.msg);
}
})
.catch((err) => {
this.$message.error(err.toString());
});