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.
 
 
 
 

113 lines
3.1 KiB

import { getToken, deleteToken } from '@/utils/token'
import feedback from '@/utils/feedback'
export const BASE_PATH = '/api/v2'
type Options = {
url: string,
method?: 'GET' | 'POST' | 'PUT' | 'DELETE',
headers?: Record<string, string>,
query?: Record<string, any>,
params?: Record<string, any>,
body?: string | FormData | Record<string, any>,
showErrorMsg: bool
};
function get(options: Options) {
options.method = 'GET';
return ajax(options.url, options)
}
function post(options: Options) {
options.method = 'POST';
return ajax(options.url, options)
}
function put(options: Options) {
options.method = 'PUT';
return ajax(options.url, options)
}
function del(options: Options) {
options.method = 'DELETE';
return ajax(options.url, options)
}
let isRelogin = false;
function ajax(url: string, options: Options) {
const headers: Record<string, string> = {
"Authorization": getToken()
};
let body: string | FormData;
if (options?.params && Object.keys(options.params).length > 0) {
if (options.method === 'GET') {
options.query = options.params;
} else {
body = JSON.stringify(options.params);
}
}
if (options?.query) {
// 解决 query 的值为 undefined 的情况
if (options.query instanceof Object) {
const params = {}
for (let k of Object.keys(options.query)) {
if (options.query[k] === undefined || options.query[k] === null) {
continue;
}
params[k] = options.query[k]
}
url += (url.indexOf('?') > -1 ? '&' : '?') + new URLSearchParams(params).toString();
} else {
url += (url.indexOf('?') > -1 ? '&' : '?') + new URLSearchParams(options.query).toString();
}
}
if (options?.body) {
if (options.body instanceof FormData) {
body = options.body;
} else {
headers["Content-Type"] = "application/json"
if (options.body instanceof String) {
body = options.body;
}
if (options.body instanceof Array || (options.body instanceof Object && Object.keys(options.body).length > 0)) {
body = JSON.stringify(options.body);
}
}
}
return new Promise((resolve, reject) => {
fetch(`${BASE_PATH}${url}`, {
method: options.method,
body: body,
headers: { ...headers, ...options.headers }
}).then(response => {
if (response.status === 413) {
return;
}
return response.json();
}).then(res => {
if (res.code === 200 || res.httpStatusCode===0) {
resolve(res.data)
} else {
let message = res.message;
if (res.code === 401) {
deleteToken()
return
}
feedback.msgError(message)
reject(res)
}
})
})
}
const request = {
get,
post,
put,
del
}
export default request;