在前端开发中,经常需要调用后端 API 接口,而使用 fetch 作为请求工具已经成为了一种主流的方式。而在使用 fetch 时,往往需要进行一些兼容性、异常处理等操作,这时就可以使用 npm 包 @turist/fetch 来简化操作。本篇文章将介绍如何使用 @turist/fetch。
安装 @turist/fetch
yarn add @turist/fetch # or npm install --save @turist/fetch
使用 @turist/fetch
使用 @turist/fetch 的时候,需要先进行初始化。使用 fetch.init()
方法即可。
import fetch from '@turist/fetch'; fetch.init({ // 在这里传入配置参数 });
配置参数
常见的配置参数如下:
baseURL
: 接口基地址timeout
: 请求超时时间headers
: 请求头withCredentials
: 是否带上跨域 cookie
发送请求
使用 @turist/fetch 发送请求时,可以直接使用支持的请求方法,如 get、post、put、delete 等。
import fetch from '@turist/fetch'; fetch.get('/api/user').then(response => { console.log(response); }).catch(error => { console.log(error); });
同时,可以在请求中使用请求参数、请求头等。
-- -------------------- ---- ------- ------ ----- ---- ---------------- ----------------------- - ----- ----- - - - -------- - --------------- ------------------ - ---------------- -- - ---------------------- -------------- -- - ------------------- ---展开代码
异常处理
使用 @turist/fetch 进行请求时,无需手动处理常见的异常,如 Timeout、404 等,@turist/fetch 会自动帮我们处理。
示例
以下是使用 @turist/fetch 调用 GitHub API 的示例代码。
-- -------------------- ---- ------- ------ ----- ---- ---------------- ------------ -------- ------------------------- -------- - ------- ------------------ - --- ------------------------------------------ -- - --------------------------- -------------- -- - ------------------- ---展开代码
以上代码用于获取 GitHub 上用户名为 turist85 的用户信息。可以看到,在配置中将 GitHub API 的基地址设置为了 baseURL,并且设置了请求头中的 Accept 为 application/json,这样我们就可以得到相应的数据格式。
总结
本篇文章介绍了如何使用 @turist/fetch 库来简化前端请求操作。主要包括初始化、发送请求、异常处理等内容。通过使用 @turist/fetch,不仅可以减少代码量,还能提高代码的健壮性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/5f2bb7553b0ab45f74a8bb52