公司演示版e鹿悦游
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
CjyTravel/plugin/util/AjaxProxy.js

109 lines
2.5 KiB

import ajax from "./Ajax";
// true 启用代理, false 禁用代理
const UseProxy = false;
// 代理服务器地址.
const AjaxProxyHost = "http://localhost:8080";
// api 前缀.
const ApiProxy = "/api/v1";
function getApiUrl(srcUrl) {
let sep = '/';
if (srcUrl.indexOf(ApiProxy) !== 0) {
if (srcUrl.indexOf('/')===0){
// 包含 /
sep = ''
}
srcUrl = ApiProxy + sep + srcUrl
}
return srcUrl
}
// 创建一个 ajax 代理
function NewProxy() {
return {
callbackMap: {},
// request_id, url, param , method, content_type , param
requestList: [],
get: function (url, data = undefined, success = undefined) {
if (!UseProxy) {
ajax.get(url, data, success);
return;
}
let requestId = this.requestList.length;
let obj = {};
obj.request_id = requestId;
obj.method = "get";
obj.url = getApiUrl(url);
if (typeof data === "function") {
this.callbackMap[requestId] = data;
obj.param = null;
} else {
this.callbackMap[requestId] = success;
obj.param = data;
}
this.requestList.push(obj);
},
post: function (url, data, success = undefined) {
if (!UseProxy) {
ajax.post(url, data, success);
return;
}
let requestId = this.requestList.length;
let obj = {};
obj.request_id = requestId;
obj.method = "post";
obj.url = getApiUrl(url);
this.callbackMap[requestId] = success;
obj.param = data;
this.requestList.push(obj);
},
send: function () {
if (!UseProxy) {
return;
}
let t = this;
ajax.ajax({
method: 'post',
url: AjaxProxyHost + '/request-proxy',
header: {
'Content-Type': 'application/json;charset=utf-8'
},
data: t.requestList,
success: function (resp) {
let m = t.callbackMap;
if (resp.code === 200 || resp.code === 0) {
for (let id in resp.data) {
let func = m[id];
if (func) {
func(resp.data[id].data)
} else {
console.log(id + " 回调为空!!")
}
}
} else {
console.log(resp);
alert("出错了!!")
}
}
});
// 执行完毕后 清空 requestList.
t.requestList = [];
}
}
}
// 全局的 ajax proxy 变量
const $ = NewProxy();
// 全局的 ajax proxy 变量
export {$}
export default {
NewProxy
}