axios请求之前带上全局参数
程序员文章站
2022-08-12 09:37:06
// 测试地址const API = { local:'XXXXX', online:'XXXXX', };//axios固定参数,定义全局变量//方法一:var login_key,uid;function getUrlParam(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]......
// 测试地址
const API = {
local:'XXXXX',
online:'XXXXX',
};
//axios固定参数,定义全局变量
//方法一:
var login_key,uid;
function getUrlParam(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.hash.substr(1).match(reg);
if (r!=null) return unescape(r[2]); return null;
}
function getQueryVariable(val) {
var query = window.location.hash.substring(1);
var vars = query.split("&");
if( val == 'uid'){
for (var i=0;i<vars.length;i++) {
var rps = vars[0];
return rps.split("=")[1];
}
return(false);
}
}
login_key = getUrlParam('login_key');
uid = getQueryVariable('uid');
-------------------------------------------------------------------------------------------------------------------
//方法二:
var login_key,uid;
function request(paramName) {
var paramValue = "";
var params = window.location.href.split('?')[1];
if (params == null || params == "")
return paramValue;
var arr = params.split('&');
if (arr.length >= 1) {
for (var i = 0; i < arr.length; i++) {
var name = arr[i].substring(0, arr[i].indexOf("="));
if (name == paramName) {
var begin = arr[i].indexOf("=");
var end = arr[i].length;
paramValue = arr[i].substring(begin + 1, end);
break;
}
}
}
return paramValue;
}
login_key = request('login_key');
uid = request('uid');
------------------------------------------------------------------------------------------------------------------
//production 为生产环境
if( process.env.NODE_ENV != 'production' ){
axios.defaults.baseURL = API.local;
}else{
axios.defaults.baseURL = API.online;
}
axios.defaults.timeout = 6000;
//http request 拦截器
axios.interceptors.request.use(
config => {
config.data = {
...config.data,
login_key:login_key,
uid:uid
}
config.data = qs.stringify(config.data);
config.headers = {
'Content-Type':'application/x-www-form-urlencoded'
};
return config;
},
err => {
return Promise.reject(err);
}
);
//http response 拦截器
axios.interceptors.response.use(
response => {
if(response.status == 200){
// console.log(response.data.error_code);
if (response.data.error_code == 10001) {
if(window.AnalyticsWebInterface){ // 安卓
window.AnalyticsWebInterface.postMessage ('{loginInvalid: {}}');
}else if(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.firebase){ // IOS
window.webkit.messageHandlers.firebase.postMessage({loginInvalid: {}});
}else{
alert('登录失效');
}
}else{
return response.data;
}
}
},
error => {
return Promise.reject(error.data)
}
);
原文:https://blog.csdn.net/Amy_cloud/article/details/82685359
本文地址:https://blog.csdn.net/qq_32963841/article/details/85988845
上一篇: 令人吐槽的字符串遍历匹配机制