105 lines
3.1 KiB
TypeScript

import {toast} from "../components/message";
export type HttpMethod = 'get' | 'post' | 'delete' | 'put'
export enum RequestDataContentType {
JSON = 'application/json;charset=UTF-8',
FORM = 'application/x-www-form-urlencoded;charset=UTF-8',
FORM_DATA = 'multipart/form-data;charset=UTF-8',
}
export const httpConfig = {
baseURL: '',
globalErrorHandler: {
1201: '请求参数不合法'
}
}
export type ResponseModel<T> = {
code: number
message: string
data: T
trace?: string
}
class Http {
post<T>(url, data) {
return this.request<T>(url, data)
}
get<T>(url, data = null) {
return this.request<T>(url, data, 'get')
}
/**
* GET /xxxx?a=1&b=2
* NAME: value
* NAME2: value
* ....
*
* POSTDATA
*
*
* @param url
* @param method
* @param data
*/
request<T>(url: string, data: any = null, method: HttpMethod = 'post', type: 'normal' | 'form' = 'normal') {
return new Promise<T>((resolve, reject) => {
let contentType = RequestDataContentType.FORM;
if (data) {
if (type === 'form') {
const form = new FormData();
for (const key in data) {
form.append(key, data[key]);
}
data = form; // 将data有{} => formData
contentType = RequestDataContentType.FORM_DATA; // 由于使用formData
method = 'post';
} else if (method == 'post') {
// 将数据对象 转成json
data = JSON.stringify(data);
contentType = RequestDataContentType.JSON;
} else {
// 装对象转成 key=value&key=value
const params = [];
for (const key in data) {
params.push(`${key}=${data[key]}`);
}
data = params.join('&')
}
}
fetch(httpConfig.baseURL + url, {
method,
body: data,
headers: {
'Content-Type': contentType
}
})
.then(res => res.json()) // 只要json的响应数据
.then((res: ResponseModel<T>) => {
const {code, data, message} = res;
if (code !== 0) {
const err = httpConfig.globalErrorHandler[code]
// 需要统一处理数据
if (code === 403) {
toast("登录凭证无效或者已过期")
return;
} else if (err) {
toast(httpConfig.globalErrorHandler[code])
return;
}
reject(Error(res.message))
return;
}
resolve(res.data)
})
.catch(() => {
})
});
}
}
const http = new Http();
export default http