介绍一个请求库 - Undici几个 API 的使用方式

网络 通信技术
本文只是介绍了 undici 几个 api 的使用方式,看起来 undici 上手难道还是比较低的。但是兼容性还不太行,比如,fetch 只支持 node@v16.5.0 以上的版本。

[[430223]]

前言

在浏览器中,如果想发起一个请求,我们以前会使用到 xhr,不过这种底层 api,往往调用方式比较简陋。为了提高开发效率, jQuery 的 $.ajax 可能是最好的选择,好在后来出现了更加现代化的 fetch api 。

但是考虑到 fetch 的兼容性,而且它也不支持一些全局性的配置,以及请求中断,在实际的使用过程中,我们可能会用到 axios 请求库,来进行一些请求。到了 Node.js 中,几乎都会通过 request 这个库,来进行请求。遗憾的是,request 在两年前就停止维护了,在 Node.js 中需要找到一个能够替代的库还挺不容易的。

在 request 的 issues[1] 中,有一个表格推荐了一些在 Node.js 中常用的请求库:

浏览器中使用比较多的 axios,在 Node.js 中并不好用,特别是要进行文件上传的时候,会有很多意想不到的问题。

最近我在网上🏄🏿的时候,发现 Node.js 官方是有一个请求库的:undici,名字取得还挺复杂的。所以,今天的文章就来介绍一下 undici。顺便提一句,undici 是意大利语 11 的意思,好像双十一也快到了,利好茅台。

  • Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. It is also a Stranger Things reference.

上手

我们可以直接通过 npm 来安装 undici:

  1. npm install undici -S 

undici 对外暴露一个对象,该对象下面提供了几个 API:

  • undici.fetch:发起一个请求,和浏览器中的 fetch 方法一致;
  • undici.request:发起一个请求,和 request 库有点类似,该方法支持 Promise;
  • undici.stream:处理文件流,可以用来进行文件的下载;

undici.fetch

注意:该方法需要 node 版本 >= v16.5.0

在通过 undici.fetch 请求服务之前,需要先通过 koa 启动一个简单登录服务。

  1. const Koa = require('koa'
  2. const bodyParser = require('koa-bodyparser'
  3.  
  4. const app = new Koa() 
  5.  
  6. app.use(bodyParser()) 
  7. app.use(ctx => { 
  8.   const { url, method, body } = ctx.request 
  9.   if (url === '/login') { 
  10.     if (method === 'POST') { 
  11.       if (body.account === 'shenfq' && body.password === '123456') { 
  12.         ctx.body = JSON.stringify({ 
  13.           name'shenfq'
  14.           mobile: '130xxxxxx' 
  15.         }) 
  16.         return 
  17.       } 
  18.     } 
  19.   } 
  20.   ctx.status = 404 
  21.   ctx.body = JSON.stringify({}) 
  22. }) 
  23.  
  24. app.listen(3100) 

上面代码很简单,只支持接受一个 POST 方法到 /login 路由。下面使用 undici.fetch 发起一个 POST 请求。

  1. const { fetch } = require('undici'
  2.  
  3. const bootstrap = async () => { 
  4.   const api = 'http://localhost:3100/login' 
  5.   const rsp = await fetch(api, { 
  6.     method: 'POST'
  7.     headers: { 
  8.       'content-type''application/json' 
  9.     }, 
  10.     body: JSON.stringify({ 
  11.       account: 'shenfq'
  12.       password'123456' 
  13.     }) 
  14.   }) 
  15.   if (rsp.status !== 200) { 
  16.     console.log(rsp.status, '请求失败'
  17.     return 
  18.   } 
  19.   const json = await rsp.json() 
  20.   console.log(rsp.status, json) 
  21.  
  22. bootstrap() 

如果将请求的方式改为 GET,就会返回 404。

  1. const rsp = await fetch(api, { 
  2.   method: 'GET' 
  3. }) 

undici.request

undici.request 的调用方式与 undici.fetch 类似,传参形式也差不多

  1. const { request } = require('undici'
  2.  
  3. const bootstrap = async () => { 
  4.   const api = 'http://localhost:3100/login' 
  5.   const { body, statusCode } = await request(api, { 
  6.     method: 'POST'
  7.     headers: { 
  8.       'content-type''application/json' 
  9.     }, 
  10.     body: JSON.stringify({ 
  11.       account: 'shenfq'
  12.       password'123456' 
  13.     }) 
  14.   }) 
  15.   const json = await body.json() 
  16.   console.log(statusCode, json) 
  17.  
  18. bootstrap() 

只是返回结果有点不一样,request 方法返回的 http 响应结果在 body 属性中,而且该属性也支持同 fetch 类似的 .json()/.text() 等方法。

中断请求

安装 abort-controller 库,然后实例化 abort-controller,将中断信号传入 request 配置中。

  1. npm i abort-controller 

 

  1. const undici = require('undici'
  2. const AbortController = require('abort-controller'
  3.  
  4. // 实例化 abort-controller 
  5. const abortController = new AbortController() 
  6. undici.request('http://127.0.0.1:3100', { 
  7.   method: 'GET'
  8.   // 传入中断信号量 
  9.   signal: abortController.signal, 
  10. }).then(({ statusCode, body }) => { 
  11.   body.on('data', (data) => { 
  12.     console.log(statusCode, data.toString()) 
  13.   }) 
  14. }) 

我们运行代码,发现是可以请求成功的,是因为我们没有主动调用中断方法。

  1. undici.request('http://127.0.0.1:3100', { 
  2.   method: 'GET'
  3.   signal: abortController.signal, 
  4. }).then(({ statusCode, body }) => { 
  5.   console.log('请求成功'
  6.   body.on('data', (data) => { 
  7.     console.log(statusCode, data.toString()) 
  8.   }) 
  9. }).catch(error => { 
  10.   // 捕获由于中断触发的错误 
  11.   console.log('error', error.name
  12. }) 
  13.  
  14. // 调用中断 
  15. abortController.abort() 

现在运行代码会发现,并没有输出 请求成功 的日志,进入了 catch 逻辑,成功的进行了请求的中断。

undici.steam

undici.steam 方法可以用来进行文件下载,或者接口代理。

文件下载

  1. const fs = require('fs'
  2. const { stream } = require('undici'
  3.  
  4. const out = fs.createWriteStream('./宋代-哥窑-金丝铁线.jpg'
  5. const url = 'https://img.dpm.org.cn/Uploads/Picture/dc/cegift/cegift6389.jpg' 
  6.  
  7. stream(url, { opaque: out }, ({ opaque }) => opaque) 

接口代理

  1. const http = require('http'
  2. const undici = require('undici'
  3.  
  4. // 将 3100 端口的请求,代理到 80 端口 
  5. const client = new undici.Client('http://localhost'
  6. http.createServer((req, res) => { 
  7.   const { url, method } = req 
  8.   client.stream( 
  9.     { method, path: url,opaque: res }, 
  10.     ({ opaque }) => opaque 
  11.   ) 
  12. }).listen(3100) 

总结

本文只是介绍了 undici 几个 api 的使用方式,看起来 undici 上手难道还是比较低的。但是兼容性还不太行,比如,fetch 只支持 node@v16.5.0 以上的版本。

对于这种比较新的库,个人还是建议多观望一段时间,虽然 request 已经废弃了,我们还是使用一些经过较长时间考验过的库,比如,egg 框架中使用的 urllib[7],还有一个 node-fetch[8],上手难道也比较低,与浏览器中的 fetch api 使用方式一致。

参考资料

[1]issues: https://github.com/request/request/issues/3143

[2]node-fetch: https://www.npmjs.com/package/node-fetch

[3]got: https://www.npmjs.com/package/got

[4]axios: https://www.npmjs.com/package/axios

[5]superagent: https://www.npmjs.com/package/superagent

[6]urllib: https://www.npmjs.com/package/urllib

[7]urllib: https://www.npmjs.com/package/urllib

[8]node-fetch: https://www.npmjs.com/package/node-fetch

 

责任编辑:姜华 来源: 自然醒的笔记本
相关推荐

2013-04-03 10:22:00

iOS开发Objective-C

2018-09-08 08:41:21

Python 3API框架API Star

2013-07-01 11:01:22

API设计API

2015-06-02 10:24:43

iOS网络请求降低耦合

2015-06-02 09:51:40

iOS网络请求封装接口

2021-07-14 17:39:46

ReactRails API前端组件

2020-11-09 06:38:00

ninja构建方式构建系统

2020-09-22 07:50:23

API接口业务

2023-06-01 08:24:08

OpenAIChatGPTPython

2010-04-15 15:42:11

Oracle数据库

2018-07-30 16:31:00

javascriptaxioshttp

2011-08-15 11:24:46

SQL Server事务

2013-01-24 09:49:58

创业华为辞职

2023-08-01 07:25:38

Expresso框架API

2022-10-08 00:00:00

AdminUser数据库鉴权

2023-04-10 14:20:47

ChatGPTRESTAPI

2023-02-01 08:04:07

测试flask网页

2021-01-25 13:45:14

模型人工智能深度学习

2013-12-05 10:50:13

2024-02-19 08:26:59

wxPython界面库开发
点赞
收藏

51CTO技术栈公众号