1,新建request.js文件,并安装相应插件
// 对axios的二次封装
import axios from 'axios'
import qs from 'qs';
let base_url = ""
//根据不同页面 访问 不同 域名
if (location.hostname == "wxroom-test.nbaidai.com") {
base_url = "········"
}
else if (location.hostname == "czq-test.jmc.com.cn" || location.hostname == "localhost") {
base_url = "·······"
}
else if (location.hostname == "czq.jmc.com.cn") {
base_url = "······"
}
let xhr = axios.create({
baseURL: base_url,
timeout: 60000,
withCredentials: false,
validateStatus: function (status) {
//需要放开,否则后台返回个401之类的 我们拿不到response
return status >= 200 && status < 500 // default
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
})
if (process.env.NODE_ENV != 'production') {
let _memberInfo = document.cookie.match(/memberInfo=([^;]*)/i);
if (!Array.isArray(_memberInfo)) {
document.cookie = `memberInfo=${window.btoa(JSON.stringify({ uid: 3, token: '466c711cfac4354447e86e99114547c7', expires: 1652078361, utype: 1 }))}`;
}
}
xhr.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
// 如果sessionStorage.getItem("token")有token,那就赋值给当前请求的接口中
if (sessionStorage.getItem("token")) {
config.headers.common['Authorization'] = sessionStorage.getItem("token");
}
const _memberInfo = document.cookie.match(/memberInfo=([^;]*)/i);
try {
let memberInfo = {};
if (!Array.isArray(_memberInfo)) {
return Promise.reject('no permission');
}
// memberInfo = JSON.parse(window.atob(_memberInfo[1]));
// memberInfo = JSON.parse(window.decodeURIComponent(escape(window.atob(_memberInfo[1]))));
memberInfo = JSON.parse(window.decodeURIComponent(encodeURIComponent(window.atob(_memberInfo[1]))))
// console.log(memberInfo, "cookies success");
// console.log(meber, "cookies try");
let me = { uid: memberInfo.uid, token: memberInfo.token, utype: memberInfo.utype }
if (config.method.toLowerCase() == 'get') {
if (config.params != null && typeof config.params == 'object') {
config.params = Object.assign({}, config.params, me);
} else {
config.params = me;
}
} else if (config.method.toLowerCase() == 'post') {
if (config.data != null && typeof config.data == 'object') {
config.data = Object.assign({}, config.data, me);
} else {
config.data = me;
}
config.data = qs.stringify(config.data);
}
} catch (err) {
console.log(err, 'cookies error');
}
return config
}, function (error) {
// 对请求错误做些什么
// router.push('/login');
return Promise.reject(error);
})
xhr.interceptors.response.use(function (response) {
// 如果返回401,证明token失效,返回到登录页面
if (response.data.code == 401) {
// router.push('/login')
}
// 对响应数据做点什么
return response.data;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error)
})
export default xhr
2,main.js引入
import xhr from './api/request.js';
Vue.prototype.$http = xhr;
3,页面数据请求
let params = {};
this.$http.get("/v1/weapon/list", { params }).then((res) => {
if (res.code == 0) {
} else {
this.$message({
message: res.msg,
type: "warning",
});
}
});