当需要请求的基地址变化的时候,可以将基地址配置成一个config.json文件放在服务器上,在main.js中读取配置的地址,从而改变请求的基地址.
1.在main.js中获取跳转的地址
axios
.get("config.json")
.then(res => {
Vue.prototype.platformUrl = res.data.VUE_APP_PLATFORM_API_PATHONE;
sessionStorage.setItem(
"platformUrl",
JSON.stringify(Vue.prototype.platformUrl)
);
Vue.prototype.casUrl = res.data.VUE_APP_CAS_PATH;
Vue.prototype.jwtUrl = res.data.VUE_APP_JWT_PATH;
Vue.prototype.platformGatewayUrl = res.data.VUE_APP_PLATFORM_API_PATH;
if (jwt == null) {
// getToken(Vue.prototype.jwtUrl, Vue.prototype.casUrl);
// const code = window.location.href.split('=')[1];
const params = new URLSearchParams(window.location.search);
let code = params.get('code')
if (code == null) {
getToken(Vue.prototype.jwtUrl, Vue.prototype.casUrl)
} else {
const jtcode = code.split("#/")[0]
tjLogin(jtcode, res.data.VUE_APP_PLATFORM_API_PATH, res.data.CLIENT_ID, res.data.CLIENT_SECRET, res.data.redirectUri)
}
} else {
if (sessionStorage.getItem("isuserConfig")) {
findMenu(JSON.parse(sessionStorage.getItem("isuserConfig")).userCode);
}
if (sessionStorage.getItem("userConfigInfo")) {
findMenu(JSON.parse(sessionStorage.getItem("userConfigInfo")).userCode);
}
if (sessionStorage.getItem("userConfig")) {
findMenu(JSON.parse(sessionStorage.getItem("userConfig")).userCode);
}
}
})
.catch(err => {
console.log(err);
});
2.配置require.js的基地址可变
import axios from "axios";
export function request(config) {
const instance = axios.create({
baseURL: JSON.parse(sessionStorage.getItem("platformUrl")),
// baseURL: "/api",
timeout: 5000
});
instance.interceptors.request.use(
config => {
const jwt = sessionStorage.getItem("jwt");
if (jwt != null) {
config.headers.Authorization = jwt;
}
return config;
},
err => {
console.log("请求拦截err: " + err);
}
);
instance.interceptors.response.use(
res => {
return res.data;
},
err => {
console.log("响应拦截err: " + err);
}
);
return instance(config);
}