封装fetch
在项目开发中,我们可能用到fetch来想后端请求数据,如果在请求数据的每个地方都直接用fetch可能会显得非常冗杂,所以我们要来自己封装一下。
apiUrl 是从环境变量中获取到的api请求地址
const apiUrl = process.env.REACT_APP_API_URL
interface Config extends RequestInit {
data?: object,
token?: string,
}
//? 第二个参数 给予 默认值 {} 变成可选参数
export const http = (enpoint: string, { data, token, headers, ...customConfig }: Config = {}) => {
const config = {
method: "GET",
headers: {
Authorization: token ? token : '',
'Content-Type': data ? "application/json" : ''
},
...customConfig
}
if (config.method.toLocaleUpperCase() === 'GET') {
enpoint += `?${qs.stringify(data)}`
} else {
config.body = JSON.stringify(data)
}
return window.fetch(`${apiUrl}/${enpoint}`, config)
.then(async response => {
if (response.status === 401) {
//退出登录
await auth.logout()
// 重新加载页面
window.location.reload()
return Promise.reject({ 'message': '请重新登陆' })
}
const data = await response.json()
if (response.ok) {
return data
} else {
return Promise.reject(data)
}
}
)
}