使用fetch封装一个请求模块使用ts语言
以下是一个使用fetch封装的请求模块,使用ts语言:
interface Options {
method?: string;
headers?: any;
body?: any;
}
const request = async (url: string, options: Options = {}) => {
const { method = 'GET', headers = {}, body } = options;
try {
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
...headers
},
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
};
export default request;
使用时,可以像下面这样调用:
import request from './request';
const fetchUser = async () => {
const user = await request('https://jsonplaceholder.typicode.com/users/1');
console.log(user);
};
fetchUser();
此模块支持传递请求方法、请求头和请求体。默认使用GET方法和JSON请求头。如果请求成功,则会返回JSON格式的数据。如果请求失败,则会在控制台输出错误信息。
原文地址: https://www.cveoy.top/t/topic/bCG7 著作权归作者所有。请勿转载和采集!