41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
export type HttpMethod = 'get' | 'post' | 'delete' | 'put'
|
|
|
|
export const httpConfig = {
|
|
baseURL: ''
|
|
}
|
|
export type ResponseModel<T> = {
|
|
code: number
|
|
message: string
|
|
data: T
|
|
trace?: string
|
|
}
|
|
|
|
class Http {
|
|
post<T>(url, data) {
|
|
return this.request<T>(url, 'post', data)
|
|
}
|
|
|
|
request<T>(url: string, method: HttpMethod, data: any = null) {
|
|
return new Promise<ResponseModel<T>>((resolve, reject) => {
|
|
|
|
fetch(httpConfig.baseURL + url, {
|
|
method,
|
|
body: JSON.stringify(data),
|
|
headers: {
|
|
'Content-Type': 'application/json;charset=utf-8'
|
|
}
|
|
})
|
|
.then(res => res.json()) // 只要json的响应数据
|
|
.then((res: ResponseModel<T>) => {
|
|
if (res.code !== 0) {
|
|
reject(Error(res.message))
|
|
return;
|
|
}
|
|
resolve(res.data)
|
|
}).catch(reject)
|
|
});
|
|
}
|
|
}
|
|
|
|
const http = new Http();
|
|
export default http |