提交 2120bd4e 作者: 翁进城

请求方法优化

上级 60f699d4
const config = {
baseUrl: 'http://192.168.3.111:8099'
}
export default config;
\ No newline at end of file
import useSWR, { SWRResponse } from "swr";
import config from './config';
/**
* 请求封装
* @param url 请求url
......@@ -6,7 +7,7 @@ import useSWR, { SWRResponse } from "swr";
* @param data 请求的参数
* @returns Promise<Response>
*/
export default function request(url: string, method: String = 'get', data: any): SWRResponse {
export default function request(url: string, method: String = 'get', data?: any): Promise<Response> {
let options = {};
switch (method.toLowerCase()) {
......@@ -32,11 +33,27 @@ export default function request(url: string, method: String = 'get', data: any):
break;
}
const fetcher = (url:string) => fetch(url, options)
.then((r) => r.json())
return fetch(config.baseUrl + url, options)
.then((r) => {
try{
return r.json()
}catch(e){
console.error(e);
}
return {
code: '-1',
message: '请求失败',
result: null
}
})
.then((data) => {
return data;
});
}
return useSWR(url, fetcher)
//准备响应结构
export interface Response<T> {
code: string,
message: string,
result: T
}
\ No newline at end of file
import useSWR, { SWRResponse } from "swr";
import config from './config';
/**
* 请求封装
* @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(config.baseUrl + url, options)
.then((r) => r.json())
.then((data) => {
return data;
});
return useSWR(url, fetcher)
}
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论