vue2 使用场景:项目中,有固定的请求域名,而有某些接口是其他域名
@/utils/request.js 固定请求域名
import axios from 'axios'
import Vue from 'vue'
let baseURL = ''
switch (window.location.hostname) {
case 'localhost': // 本地
case '127.0.0.1':
case '172.25.112.0':
baseURL = 'https://csapi.test/'
break
case 'www.kaifa.top': // 开发(网址)
baseURL = 'https://kfapi.test.top/'
break
case 'www.ceshi.top': // 测试(网址)
baseURL = 'https://csapi.test.top/'
break
case 'www.zhengshi.cn': // 正式(网址)
baseURL = 'https://api.zheng.cn/'
break
}
const service = axios.create({
baseURL,
timeout: 180000
})
service.interceptors.response.use(
response => {
return response
}
)
Vue.prototype.$http = service
export default baseURL
@/utils/request_ip.js 设置动态请求域名
import axios from 'axios';
import Vue from 'vue'
import { getHashParam } from '@/utils/tool';
// 获取ip的值 url链接?后面携带的参数 ?id=12&ip=172.21.999.50:8000
// 从 URL 参数中获取域名
const getBaseURL = () => {
const myParam = getHashParam('ip');
let ip;
// 如果 :变成了%3A 则替换 %3A 为 冒号
if(myParam.search('%3A')){
ip = myParam.replace(/%3A/g, ':');
}else{
ip = myParam;
}
// 如果没有端口号,添加默认端口号
if (!ip.includes(':')) ip += ':8000'
if (ip) {
return `http://${ip}/`;
}
// 默认回退到当前域名
// const { protocol, hostname, port } = window.location;
// return `${protocol}//${hostname}${port ? `:${port}` : ''}`;
};
console.log( getBaseURL(),'获取到ip地址')
const instance = axios.create({
baseURL: getBaseURL(), // 动态获取的域名
timeout: 180000,
// headers: {
// 'Content-Type': 'application/json',
// }
});
instance.interceptors.response.use(
response => {
return response
}
)
Vue.prototype.$httpip = instance
@/utils/tool.js 获取 url链接 携带的参数
export function getHashParam(param) {
const hash = window.location.hash.substring(1); // 移除开头的'#'
const params = hash.split('&').reduce((acc, curr) => {
const [key, value] = curr.split('=');
acc[key] = value;
return acc;
}, {});
return params[param] ? decodeURIComponent(params[param]) : null;
}
在 main.js 文件中 引入
import '@/utils/request'
import '@/utils/request_ip'
在vue页面中使用 @/view/index.vue
methods:{
// 固定的请求域名 示例 this.$http
getYishuKaoshiList() {
let data = {
page: 1
}
this.$http.post('getList', data).then(res => {
if (res.data.code == 1) {}
});
},
// 动态获取到的ip域名 请求接口 示例 this.$http_ip
dongFn(item) {
let data = {
project_id:1
}
this.$httpip.post('decrypt',data).then(res => {
if (res.data.code == 1) {
this.$Message.success('成功');
}else{
this.$Message.error(res.data.msg);
}
});
},
}