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.
 
 
 

54 lines
1.3 KiB

//复制时倒入qs
// @ts-ignore
import qs from "qs";
const API_SERVER = process.env.NEXT_PUBLIC_WEB_SITE
export interface Config<T> extends RequestInit {
token?: string
data?: T
method?: 'POST' | 'GET'
}
interface IError {
status: number
details: [],
message: string
metadata: any
reason: string
}
const http = async <T, V>(endpoint: string, {data, token, headers, ...customConfig}: Config<T>) => {
const config = {
method: "GET",
headers: {
Authorization: token ? `Bearer ${token}` : '',
'Content-type': data ? 'application/json' : '',
},
...customConfig
}
if (config.method.toUpperCase() === "GET") {
endpoint += `?${qs.stringify(data)}`
} else {
config.body = JSON.stringify(data || {})
}
console.log(API_SERVER + endpoint, token)
return fetch(API_SERVER + endpoint, config).then(async response => {
if (response.status == 401) {
if (typeof window != 'undefined') {
// window.location.reload();
}
return Promise.reject({message: "请重新登录", status: 401})
}
const data = await response.json();
if (response.ok) {
return data as V;
} else {
return Promise.reject(data as IError);
}
})
}
export {
http
}