提交 ea160631 作者: 翁进城

请求封装

上级 b59d98cc
import useSWR, { SWRResponse } from "swr";
/**
* 请求封装
* @param url 请求url
* @param method 请求方法类型
* @param data 请求的参数
* @returns Promise<Response>
*/
export default function request(url: string, method: String = 'get', data: any): SWRResponse {
let options = {};
switch (method.toLowerCase()) {
case 'get':
let params = new URLSearchParams();
if (data) {
Object.keys(data).forEach((key) => {
params.append(key, data[key]);
})
url += params;
}
break;
case 'post':
options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
break;
}
const fetcher = (url:string) => fetch(url, options)
.then((r) => r.json())
.then((data) => {
return data;
});
return useSWR(url, fetcher)
}
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论