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.
crmeb/app/utils/request.js

151 lines
3.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import {
HTTP_REQUEST_URL,
HTTP_ADMIN_URL,
HEADER,
TOKENNAME,
HEADERPARAMS
} from '@/config/app';
import {
toLogin,
checkLogin
} from '../libs/login';
import store from '../store';
import JSONBig from 'json-bigint';
const JSONbigString = JSONBig({ storeAsString: true });
/**
* 发送请求
*/
function baseRequest(url, method, data, {
noAuth = false,
noVerify = false,
useAdminUrl = false
}, params) {
let Url = useAdminUrl ? HTTP_ADMIN_URL : HTTP_REQUEST_URL, header = HEADER
if (params != undefined) {
header = HEADERPARAMS;
}
if (!noAuth) {
//登录过期自动登录
if (!store.state.app.token && !checkLogin()) {
toLogin();
return Promise.reject({
msg: '未登录'
});
}
}
if (store.state.app.token) header[TOKENNAME] = store.state.app.token;
return new Promise((reslove, reject) => {
const apiPrefix = useAdminUrl ? '/api/' : '/api/front/'
// 当使用admin URL时统一添加uid参数
let requestData = data || {};
if (useAdminUrl && store.state.app.uid) {
requestData.uid = store.state.app.uid;
}
uni.request({
url: Url + apiPrefix + url,
method: method || 'GET',
header: header,
data: requestData,
dataType: 'text',
responseType: 'text',
success: (res) => {
let data = res.data;
try {
data = JSONbigString.parse(res.data);
} catch (e) {
// JSONBig 解析失败时,使用原数据
console.warn('JSONBig 解析失败:', e);
data = JSON.parse(res.data);
}
console.debug('接口返回数据:', data);
if (noVerify)
reslove(data, res);
else if (data.code == 200)
reslove(data, res);
else if ([410000, 410001, 410002, 401].indexOf(data.code) !== -1) {
toLogin();
reject(data);
} else
reject(data.message || '系统错误');
},
fail: (msg) => {
reject('请求失败');
}
})
});
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});
/**
* 文件上传
* @param {string} filePath 文件路径
* @param {string} name 文件名称
* @param {object} formData 其他表单数据
* @param {object} options 选项
* @returns {Promise}
*/
request.uploadFile = (filePath, name = 'file', formData = {}, options = {}) => {
return new Promise((resolve, reject) => {
const Url = HTTP_ADMIN_URL;
const apiPrefix = '/api/';
let uploadUrl = Url + apiPrefix + 'admin/upload/file';
let queryObj = {
uid: store.state.app.uid,
...(options.params || {})
}
if (Object.keys(queryObj).length > 0) {
const queryString = Object.entries(queryObj)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
uploadUrl += '?' + queryString;
}
// 添加token
const header = {};
if (store.state.app.token) {
header[TOKENNAME] = store.state.app.token;
}
const uploadTask = uni.uploadFile({
url: uploadUrl,
filePath: filePath,
name: name,
header: header,
formData: formData,
success: (res) => {
if (res.statusCode === 200) {
try {
const data = JSON.parse(res.data);
if (data.code === 200) {
resolve(data.data);
} else {
reject(data.message || '上传失败');
}
} catch (e) {
reject('上传失败,返回数据格式错误');
}
} else {
reject('上传失败HTTP状态码' + res.statusCode);
}
},
fail: (err) => {
reject('上传失败:' + (err.errMsg || '未知错误'));
}
});
// 支持进度回调
if (options.onProgressUpdate) {
uploadTask.onProgressUpdate(options.onProgressUpdate);
}
});
};
export default request;