PixUI Fetch
优化后的 fetch。
1. 作者
novlan1
2. 如何使用
安装:
bash
pnpm add pixui-fetchts
import { PixFetch } from 'pixui-fetch'
PixFetch("http://www.xxx")
.then(response => {console.log("Success")})
.catch(error => {console.log("Failed")})3. 优化 fetch
传统 fetch 不会关心 AJAX 是否成功,他只关心从服务器发送请求和接收响应,如果响应失败我们需要抛出异常。
所以如果请求响应为404,但此时仍然会执行 then 里设置的 resolve 回调,如果需要处理404的情况需要额外在 resolve 里使用 response.ok 进行判断后抛出异常。
pix-fetch 对这种请求结果进行了优化,如果请求结果为2xx,则会执行 then 绑定的 resolve 回调,如果为非2xx或者请求失败则都走 reject 回调
- 传统fetch
ts
fetch('http://localhost:8080')
.then(response => {
if (response.ok) {
return response.json()
} else {
return Promise.reject('ERROR')
}
})
.then(data => console.log('Success'))
.catch(error => console.log('Failed'));- pixui-fetch
ts
PixFetch("http://www.localhost:8080")
.then(response => {console.log("Success")})
.catch(error => {console.log("Failed")})