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.
41 lines
1.3 KiB
41 lines
1.3 KiB
|
|
type HttpReqParam = {
|
|
url: string;
|
|
method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
|
|
params?: Record<string, any>;
|
|
encode?: "form" | "json"; // 入参编码类型
|
|
headers?: Record<string, any>;
|
|
};
|
|
|
|
export default async function httpRequest<T>({ url, method = "GET", params = {}, encode = "json", headers = {} }: HttpReqParam) {
|
|
// const token = sessionStorage.getItem("token");
|
|
// if (token) {
|
|
// headers = { Authorization: token, ...headers };
|
|
// }
|
|
if (method === "GET") {
|
|
const query = urlEncode(params);
|
|
const _url = query ? url + "?" + query : url;
|
|
const res = await fetch(_url, { headers });
|
|
return res.json() as Promise<T>;
|
|
} else {
|
|
const body = encode === "json" ? JSON.stringify(params) : urlEncode(params);
|
|
const _headers =
|
|
encode === "json"
|
|
? { "Content-Type": "application/json; charset=utf-8", ...headers }
|
|
: { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", ...headers };
|
|
const res = await fetch(url, { method, headers: _headers, body });
|
|
return res.json() as Promise<T>;
|
|
}
|
|
}
|
|
|
|
export function urlEncode(params?: Record<string, any>) {
|
|
let query = "";
|
|
if (params && Object.keys(params).length > 0) {
|
|
const qs = [];
|
|
for (let attr in params) {
|
|
qs.push(`${attr}=${encodeURIComponent(params[attr])}`);
|
|
}
|
|
query = qs.join("&");
|
|
}
|
|
return query;
|
|
}
|