Initial commit
This commit is contained in:
580
utils/request.js
Normal file
580
utils/request.js
Normal file
@@ -0,0 +1,580 @@
|
||||
/**
|
||||
* @description 请求配置
|
||||
*/
|
||||
import axios from "axios";
|
||||
import CryptoJS from "crypto-js";
|
||||
import { Base64 } from "js-base64";
|
||||
import { getToken, removeToken } from "./auth.js";
|
||||
import JSONBig from "json-bigint";
|
||||
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
|
||||
// export const baseUrl = "https://lingniu-gateway.demo.chinawayltd.com/";
|
||||
// export const baseUrl = "http://192.168.1.6:6902/";
|
||||
|
||||
const ENV = {
|
||||
test: {
|
||||
URL: "https://lingniu.test.chinawayltd.com/gateway/",
|
||||
},
|
||||
demo: {
|
||||
URL: "https://lingniu-gateway.demo.chinawayltd.com/",
|
||||
},
|
||||
loce: {
|
||||
URL: "http://192.168.130.136:6902/",
|
||||
},
|
||||
loce2: {
|
||||
URL: "http://192.168.110.222:6902/",
|
||||
},
|
||||
loce3: {
|
||||
URL: "http://192.168.110.23:6902/",
|
||||
},
|
||||
local: {
|
||||
URL: "http://lingniu.huixintop.com/",
|
||||
},
|
||||
online: {
|
||||
URL: "https://lnh2e.com/api/",
|
||||
},
|
||||
beta: {
|
||||
URL: "https://beta.lnh2e.com/api/",
|
||||
},
|
||||
test2: {
|
||||
URL: "http://115.230.138.233:6902/",
|
||||
},
|
||||
huixin: {
|
||||
URL: "https://lingniu.huixintop.com/",
|
||||
},
|
||||
};
|
||||
|
||||
const vega = {
|
||||
["lingniu-manager-v1"]: {
|
||||
key: "lingniu_server",
|
||||
secret: "TiDjIe7dEaNfzI7n2w9emXkXlCbLmPar",
|
||||
},
|
||||
["lingniu-export-v1"]: {
|
||||
key: "lingniu_server",
|
||||
secret: "TiDjIe7dEaNfzI7n2w9emXkXlCbLmPar",
|
||||
},
|
||||
};
|
||||
|
||||
const product = "lingniu-manager-v1";
|
||||
const uploadProduct = "lingniu-export-v1";
|
||||
const version = "v1";
|
||||
const sin_key = "lingniu_server";
|
||||
const sin_secret = "TiDjIe7dEaNfzI7n2w9emXkXlCbLmPar";
|
||||
|
||||
export const baseUrl = ENV.beta.URL;
|
||||
console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + baseUrl);
|
||||
class REQUEST {
|
||||
static request(config) {
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
...config,
|
||||
success: (res) => {
|
||||
resolve(res.data.data);
|
||||
},
|
||||
fail: (e) => {
|
||||
reject(e);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static get(url, data, config) {
|
||||
return this.request({
|
||||
url: url, //仅为示例,并非真实接口地址。
|
||||
method: "get",
|
||||
data: data,
|
||||
...config,
|
||||
});
|
||||
}
|
||||
|
||||
static post(url, data, config = {}) {
|
||||
return this.request({
|
||||
url: url, //仅为示例,并非真实接口地址。
|
||||
method: "post",
|
||||
data: data,
|
||||
...config,
|
||||
});
|
||||
}
|
||||
|
||||
static put(url, data, config = {}) {
|
||||
return this.request({
|
||||
url: url, //仅为示例,并非真实接口地址。
|
||||
method: "put",
|
||||
data: data,
|
||||
...config,
|
||||
});
|
||||
}
|
||||
|
||||
static delete(url, data, config = {}) {
|
||||
return this.request({
|
||||
url: url, //仅为示例,并非真实接口地址。
|
||||
method: "delete",
|
||||
data: data,
|
||||
...config,
|
||||
});
|
||||
}
|
||||
|
||||
static upload(url, config = {}) {
|
||||
const _this = this;
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url,
|
||||
...config,
|
||||
success: (res) => {
|
||||
resolve(res.data);
|
||||
},
|
||||
fail: (e) => {
|
||||
reject(e);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static download(url, fileName, cb) {
|
||||
let config = {
|
||||
responseType: "blob",
|
||||
};
|
||||
_requestAxios("get", {
|
||||
url: url,
|
||||
data: {},
|
||||
config: config,
|
||||
}).then((res) => {
|
||||
if (cb) {
|
||||
cb();
|
||||
}
|
||||
const blob = new Blob([res.data]);
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = fileName || _getFileName(res);
|
||||
link.style.display = "none";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
window.URL.revokeObjectURL(link.href);
|
||||
document.body.removeChild(link);
|
||||
|
||||
function _getFileName(res) {
|
||||
let headers = res.headers;
|
||||
let contentDisposition = headers["content-disposition"];
|
||||
let reg = /(filename=)(\S)*(;)?/g;
|
||||
let fileNameArr = contentDisposition.match(reg);
|
||||
if (fileNameArr.length < 1) {
|
||||
return "template.txt";
|
||||
}
|
||||
let fileNameStr = fileNameArr[0].replace(";", "");
|
||||
let fileName = fileNameStr.replace("filename=", "");
|
||||
return decodeURI(fileName);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
static getImageUrlParam(url, data, config = {}) {
|
||||
config.params = data;
|
||||
let reg = _regurl(url);
|
||||
if (Array.isArray(reg) && reg.length >= 4) {
|
||||
const [, product, version, path] = reg;
|
||||
|
||||
const key = vega[product].key;
|
||||
const secret = vega[product].secret;
|
||||
|
||||
const timestamp = Date.now();
|
||||
const stringToSign = `GET\n${timestamp}\n/${product}/${version}${path}`;
|
||||
const sign = Base64.btoa(
|
||||
CryptoJS.HmacSHA1(stringToSign, secret).toString()
|
||||
);
|
||||
|
||||
return `g7liteSaasGatewayAppKey=${key}&g7liteSaasGatewayTimestamp=${timestamp}&g7liteSaasGatewaySign=${encodeURIComponent(
|
||||
sign
|
||||
)}&g7liteGToken=${encodeURIComponent(getToken())}`;
|
||||
} else {
|
||||
console.warn("vega配置存在问题,请检查vega相关配置");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//BlobUrl转blob数据
|
||||
function funobjectURLToBlob(blodurl, nmae) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fileManager = uni.getFileSystemManager();
|
||||
fileManager.readFile({
|
||||
filePath: `${blodurl}`,
|
||||
position: 0,
|
||||
success(res) {
|
||||
// let files = new window.File([res.data], name, {
|
||||
// type: 'image'
|
||||
// });
|
||||
// console.log(res.data)
|
||||
resolve(res);
|
||||
},
|
||||
fail(res) {
|
||||
console.error(res);
|
||||
},
|
||||
});
|
||||
// var http = new XMLHttpRequest();
|
||||
// http.open('GET', blodurl, true);
|
||||
// http.responseType = 'blob';
|
||||
// http.onload = function(e) {
|
||||
|
||||
// };
|
||||
// http.send();
|
||||
});
|
||||
}
|
||||
|
||||
function _regurl(url) {
|
||||
return url.match(/([^/]+)\/(v\d)(\/\S+)/);
|
||||
}
|
||||
|
||||
function _requestAxios(type, { url, config = {}, data = {} }) {
|
||||
console.log(/(http|https):\/\/([\w.]+\/?)\S*/.test(url));
|
||||
const reqUrl = /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
|
||||
? url
|
||||
: baseUrl + url;
|
||||
let sign = {};
|
||||
const langMapping = {
|
||||
zh: "zh_CN",
|
||||
en: "en_US",
|
||||
th: "th_TH",
|
||||
tw: "zh_TW",
|
||||
};
|
||||
if (Array.isArray(reg) && reg.length >= 4) {
|
||||
const [, product, version, path] = reg;
|
||||
let pathArr = path.split("?");
|
||||
let pathStr = pathArr[0];
|
||||
sign = _makeApiSign({
|
||||
reqType: type,
|
||||
path: pathStr,
|
||||
product,
|
||||
version,
|
||||
key: vega[product].key,
|
||||
secret: vega[product].secret,
|
||||
});
|
||||
} else {
|
||||
console.warn("vega配置存在问题,请检查vega相关配置");
|
||||
}
|
||||
|
||||
config.headers = Object.assign(
|
||||
{
|
||||
"Content-Type": "application/json",
|
||||
from_type: 1,
|
||||
},
|
||||
{
|
||||
"G7LITE-LANGUAGE": "zh_CN",
|
||||
g7liteGToken: getToken(),
|
||||
g7liteSaasGatewayAppKey: sign.key,
|
||||
g7liteSaasGatewayTimestamp: sign.timestamp,
|
||||
g7liteSaasGatewaySign: sign.sign,
|
||||
},
|
||||
config.headers
|
||||
);
|
||||
|
||||
_formatRequestData(type, config, data);
|
||||
let requestConfig = Object.assign(config, {
|
||||
method: type.toLowerCase(),
|
||||
url: reqUrl,
|
||||
});
|
||||
return axios(requestConfig)
|
||||
.then((res) => _requestThen(config, res))
|
||||
.catch((error) => _requestCatch(config, error));
|
||||
|
||||
function _requestThen(config, res) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!config.responseType || config.responseType === "json") {
|
||||
if (res.data.code === 0 && res.data.subCode === 0) {
|
||||
resolve(res.data);
|
||||
} else {
|
||||
const vegaErrorCode = [
|
||||
"330000011",
|
||||
"330000012",
|
||||
"330000013",
|
||||
"330000014",
|
||||
"330000015",
|
||||
"330000016",
|
||||
"330000017",
|
||||
"330000018",
|
||||
"330000019",
|
||||
"331040003", // gtoken not allow empty
|
||||
"331040007", // gtoken not existed
|
||||
];
|
||||
if (
|
||||
vegaErrorCode.includes("" + res.data.subCode) ||
|
||||
vegaErrorCode.includes("" + res.data.code)
|
||||
) {
|
||||
console.log("token失效");
|
||||
removeToken();
|
||||
uni.reLaunch({
|
||||
url: "pages/index/index",
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.hideErrorMsg) {
|
||||
if (res.data.subCode === 331090010) {
|
||||
uni.$u.toast("禁止访问");
|
||||
} else {
|
||||
let messageStr = "系统错误";
|
||||
if (res.data.message) {
|
||||
messageStr = res.data.message;
|
||||
}
|
||||
|
||||
if (res.data.subMessage) {
|
||||
messageStr = res.data.subMessage;
|
||||
}
|
||||
|
||||
uni.$u.toast(messageStr);
|
||||
}
|
||||
}
|
||||
reject(res);
|
||||
}
|
||||
} else {
|
||||
if (res && res.data) {
|
||||
resolve(res);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function _formatRequestData(type, config, data) {
|
||||
const isBody = ["PUT", "put", "POST", "post", "PATCH", "patch"];
|
||||
let resultData = {};
|
||||
|
||||
data.hash = Math.random() * 100000000000000;
|
||||
|
||||
if (isBody.includes(type)) {
|
||||
resultData = _trimParams(data) || {};
|
||||
|
||||
if (
|
||||
config.headers &&
|
||||
config.headers["Content-Type"] &&
|
||||
config.headers["Content-Type"].indexOf(
|
||||
"application/x-www-form-urlencoded"
|
||||
) > -1
|
||||
) {
|
||||
resultData = _formatParams(data);
|
||||
}
|
||||
config.data = resultData;
|
||||
} else {
|
||||
data = config.params || data;
|
||||
config.params = _trimParams(data) || {};
|
||||
resultData = config;
|
||||
}
|
||||
return resultData;
|
||||
}
|
||||
|
||||
function _trimParams(data) {
|
||||
if (data.constructor === Object) {
|
||||
for (let i in data) {
|
||||
if (typeof data[i] === "string") {
|
||||
data[i] = data[i].trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function _formatParams(data) {
|
||||
if (data.constructor === Object) {
|
||||
const arr = [];
|
||||
|
||||
for (const i in data) {
|
||||
arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]));
|
||||
}
|
||||
|
||||
data = arr.join("&");
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function _requestCatch(config, error = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!error.isCancel) {
|
||||
if (config.needReject) {
|
||||
reject(error);
|
||||
} else {
|
||||
const res = (error || {}).data || {};
|
||||
const messageText = res.code !== 0 ? res.message : res.subMessage;
|
||||
this.$refs.uToast.show({
|
||||
type: "error",
|
||||
message: messageText || "请求失败",
|
||||
complete() {
|
||||
params.url &&
|
||||
uni.navigateTo({
|
||||
url: params.url,
|
||||
});
|
||||
},
|
||||
});
|
||||
reject(error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function _makeApiSign(config) {
|
||||
const { reqType, path, product = "", version, key, secret } = config;
|
||||
const timestamp = Date.now();
|
||||
const stringToSign = `${reqType.toUpperCase()}\n${timestamp}\n/${product}/${version}${path}`;
|
||||
const sign = Base64.btoa(
|
||||
CryptoJS.HmacSHA1(stringToSign, secret).toString()
|
||||
);
|
||||
|
||||
return {
|
||||
key,
|
||||
sign,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function _makeApiSign(config) {
|
||||
const { reqType, path, product = "", version, key, secret } = config;
|
||||
const timestamp = Date.now();
|
||||
const stringToSign = `${reqType.toUpperCase()}\n${timestamp}\n/${product}/${version}${path}`;
|
||||
const sign = Base64.btoa(CryptoJS.HmacSHA1(stringToSign, secret).toString());
|
||||
|
||||
return {
|
||||
key,
|
||||
sign,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
async function getFormDataParams() {
|
||||
const date = new Date();
|
||||
date.setHours(date.getHours() + 1);
|
||||
const policyText = {
|
||||
expiration: date.toISOString(), // 设置policy过期时间。
|
||||
conditions: [
|
||||
// 限制上传大小。
|
||||
["content-length-range", 0, 1024 * 1024 * 1024],
|
||||
],
|
||||
};
|
||||
const credentials = await axios.get("/getToken");
|
||||
const policy = Base64.encode(JSON.stringify(policyText)); // policy必须为base64的string。
|
||||
const signature = computeSignature(credentials.AccessKeySecret, policy);
|
||||
const formData = {
|
||||
OSSAccessKeyId: credentials.AccessKeyId,
|
||||
signature,
|
||||
policy,
|
||||
"x-oss-security-token": credentials.SecurityToken,
|
||||
};
|
||||
return formData;
|
||||
}
|
||||
|
||||
uni.addInterceptor("uploadFile", {
|
||||
invoke(args) {
|
||||
// request 触发前拼接 url
|
||||
let pathArr = args.url.split("?");
|
||||
const pathStr = pathArr[0];
|
||||
args.url = baseUrl + uploadProduct + "/" + version + args.url;
|
||||
// args.url = "http://127.0.0.1:6902/"+uploadProduct+"/"+version+ args.url
|
||||
const sign = _makeApiSign({
|
||||
reqType: "post",
|
||||
path: pathStr,
|
||||
uploadProduct,
|
||||
version,
|
||||
key: sin_key,
|
||||
secret: sin_secret,
|
||||
});
|
||||
args.header = {
|
||||
...args.header,
|
||||
"G7lite-Language": "zh_CN",
|
||||
g7liteSaasGatewayAppKey: sign.key,
|
||||
g7liteSaasGatewayTimestamp: sign.timestamp,
|
||||
g7liteSaasGatewaySign: sign.sign,
|
||||
G7litegtoken: getToken(),
|
||||
};
|
||||
},
|
||||
success(res) {},
|
||||
});
|
||||
uni.addInterceptor("request", {
|
||||
invoke(args) {
|
||||
// request 触发前拼接 url
|
||||
let pathArr = args.url.split("?");
|
||||
const pathStr = pathArr[0];
|
||||
// 如果是附件上传接口,则使用 uploadProduct
|
||||
if (pathStr == "/attachment/upload") {
|
||||
args.url = baseUrl + uploadProduct + "/" + version + args.url;
|
||||
} else if (pathStr.indexOf("/apis.map.qq.co") > -1) {
|
||||
args.url = args.url;
|
||||
} else {
|
||||
args.url = baseUrl + product + "/" + version + args.url;
|
||||
}
|
||||
//地图API单独处理
|
||||
|
||||
const sign = _makeApiSign({
|
||||
reqType: args.method,
|
||||
path: pathStr,
|
||||
product,
|
||||
version,
|
||||
key: sin_key,
|
||||
secret: sin_secret,
|
||||
});
|
||||
args.header = {
|
||||
...args.header,
|
||||
"G7lite-Language": "zh_CN",
|
||||
g7liteSaasGatewayAppKey: sign.key,
|
||||
g7liteSaasGatewayTimestamp: sign.timestamp,
|
||||
g7liteSaasGatewaySign: sign.sign,
|
||||
G7litegtoken: getToken(),
|
||||
};
|
||||
},
|
||||
success(res) {
|
||||
res.data = res.data;
|
||||
if (
|
||||
(res.data.code === 0 && res.data.subCode === 0) ||
|
||||
(res.statusCode === 200 && res.data.code === 200) || //获取地图markers接口
|
||||
(res.statusCode === 200 && res.data.status === 0) //微信泛解析地址接口
|
||||
) {
|
||||
return res.data;
|
||||
}
|
||||
const vegaErrorCode = [
|
||||
"330000011",
|
||||
"330000012",
|
||||
"330000013",
|
||||
"330000014",
|
||||
"330000015",
|
||||
"330000016",
|
||||
"330000017",
|
||||
"330000018",
|
||||
"330000019",
|
||||
"331040003", // gtoken not allow empty
|
||||
"331040007", // gtoken not existed
|
||||
];
|
||||
console.log("请求失败", res);
|
||||
if (
|
||||
vegaErrorCode.includes("" + res.data.subCode) ||
|
||||
vegaErrorCode.includes("" + res.data.code)
|
||||
) {
|
||||
removeToken();
|
||||
uni.reLaunch({
|
||||
url: "pages/index/index",
|
||||
});
|
||||
}
|
||||
if (res.data.subCode === 331090010) {
|
||||
uni.$u.toast("禁止访问");
|
||||
} else {
|
||||
let messageStr = "系统错误";
|
||||
if (res.data.message) {
|
||||
messageStr = res.data.message;
|
||||
}
|
||||
if (res.data.subMessage) {
|
||||
messageStr = res.data.subMessage;
|
||||
}
|
||||
if (res.data.code == 330000013) {
|
||||
messageStr = "请登录";
|
||||
}
|
||||
uni.$u.toast(messageStr);
|
||||
}
|
||||
},
|
||||
fail(err) {
|
||||
console.log("interceptor-fail", err);
|
||||
if (err.errno == "600001") {
|
||||
uni.$u.toast("请求超时");
|
||||
} else {
|
||||
uni.$u.toast(err.errMsg);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export default REQUEST;
|
||||
Reference in New Issue
Block a user