H5-ThreeDoorder/unpackage/dist/dev/app-plus/static/js/request/request.js

89 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @BaseUR 请求域名
* @HEADERTOKENNAME 请求token键名
* @Bearer 是否需要在token前拼接 Bearer字符
* */
class Request {
constructor({
BaseUR = '',
HEADERTOKENNAME = 'token',
Bearer = false
} = {}) {
this['BaseUR'] = BaseUR;
this['HEADERTOKENNAME'] = HEADERTOKENNAME;
this['Bearer'] = Bearer;
}
// URL拼接方法
url(value) {
return /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/.test(value)
}
Request(config = {}) {
// 是否存在url
try {
if (!url) {
throw '请求缺少URL参数';
}
} catch (e) {
throw new Error(e);
};
// 创建请求头对象
let header = {}
// 请类型
config['method'] = config['method'] ? config['method'].toUpperCase() : 'GET';
// 正常情况下
// GET请求使用 'application/x-www-form-urlencoded'
// POST请求使用 'application/json'
// 列外情况下会与之相反,所以将Content-Type写为根据手动传输或根据请求类型判断目前只写入GET与POST后续可扩展
header['Content-Type'] = header['Content-Type'] ? header['Content-Type'] : this.method(
config['method']);
config['header'] = header;
// url判断部分项目中不仅要调用本公司的接口还要调用其他方的接口这时候就会不使用当前公司的url端口所以将端口拼接写活
if (!this.url(config['url'])) {
url = `${this['BaseUR']}${config['url']}`
};
config['complete'] = (infor) => {
this.responseintercept(infor);
}
let Requestconfig = this.Requestintercept(config);
console.log(Requestconfig);
// 请求体
return new Promise((resolve, reject) => {
uni.request(Requestconfig)
})
}
// 请求拦截
Requestintercept(config) {
// 请求时所携带的token名称目前会存在 Authorization/ token
config['header'][this['HEADERTOKENNAME']] = `${this['Bearer']?'Bearer':''}`;
return config
}
// 响应拦截
responseintercept(infor) {
}
// 请求类型过滤
method(method) {
switch (method) {
case 'GET':
return 'application/x-www-form-urlencoded';
case 'POST':
return 'application/json';
}
}
}
const request = new Request({
BaseUR: "http://119.3.107.201:8100/prod-api/", // 测试
});
export default request;