前言

在浏览器中,如果想发动一个申请,咱们以前会应用到 xhr,不过这种底层 api,往往调用形式比拟简陋。为了进步开发效率, jQuery 的 $.ajax 可能是最好的抉择,好在起初呈现了更加现代化的 fetch api 。

然而思考到 fetch 的兼容性,而且它也不反对一些全局性的配置,以及申请中断,在理论的应用过程中,咱们可能会用到 axios 申请库,来进行一些申请。到了 Node.js 中,简直都会通过 request 这个库,来进行申请。遗憾的是,request 在两年前就进行保护了,在 Node.js 中须要找到一个可能代替的库还挺不容易的。

在 request 的 issues 中,有一个表格举荐了一些在 Node.js 中罕用的申请库:

包名包大小API格调简介
node-fetch0.4kbpromise / streamA light-weight module that brings window.fetch to Node.js
got48.4kbpromise / streamSimplified HTTP requests
axios11.9kbpromise / streamPromise based HTTP client for the browser and node.js
superagent18kbchaining / promiseSmall progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features
urllib816kbcallback / promiseHelp in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.

浏览器中应用比拟多的 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

npm install undici -S

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

  • undici.fetch:发动一个申请,和浏览器中的 fetch 办法统一;
  • undici.request:发动一个申请,和 request 库有点相似,该办法反对 Promise;
  • undici.stream:解决文件流,能够用来进行文件的下载;

undici.fetch

留神:该办法须要 node 版本 >= v16.5.0

在通过 undici.fetch 申请服务之前,须要先通过 koa 启动一个简略登录服务。

const Koa = require('koa')const bodyParser = require('koa-bodyparser')const app = new Koa()app.use(bodyParser())app.use(ctx => {  const { url, method, body } = ctx.request  if (url === '/login') {    if (method === 'POST') {      if (body.account === 'shenfq' && body.password === '123456') {        ctx.body = JSON.stringify({          name: 'shenfq',          mobile: '130xxxxxx'        })        return      }    }  }  ctx.status = 404  ctx.body = JSON.stringify({})})app.listen(3100)

下面代码很简略,只反对承受一个 POST 办法到 /login 路由。上面应用 undici.fetch 发动一个 POST 申请。

const { fetch } = require('undici')const bootstrap = async () => {  const api = 'http://localhost:3100/login'  const rsp = await fetch(api, {    method: 'POST',    headers: {      'content-type': 'application/json'    },    body: JSON.stringify({      account: 'shenfq',      password: '123456'    })  })  if (rsp.status !== 200) {    console.log(rsp.status, '申请失败')    return  }  const json = await rsp.json()  console.log(rsp.status, json)}bootstrap()

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

const rsp = await fetch(api, {  method: 'GET'})

undici.request

undici.request 的调用形式与 undici.fetch 相似,传参模式也差不多。

const { request } = require('undici')const bootstrap = async () => {  const api = 'http://localhost:3100/login'  const { body, statusCode } = await request(api, {    method: 'POST',    headers: {      'content-type': 'application/json'    },    body: JSON.stringify({      account: 'shenfq',      password: '123456'    })  })  const json = await body.json()  console.log(statusCode, json)}bootstrap()

只是返回后果有点不一样,request 办法返回的 http 响应后果在 body 属性中,而且该属性也反对同 fetch 相似的 .json()/.text() 等办法。

中断请求

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

npm i abort-controller
const undici = require('undici')const AbortController = require('abort-controller')// 实例化 abort-controllerconst abortController = new AbortController()undici.request('http://127.0.0.1:3100', {  method: 'GET',  // 传入中断信号量  signal: abortController.signal,}).then(({ statusCode, body }) => {  body.on('data', (data) => {    console.log(statusCode, data.toString())  })})

咱们运行代码,发现是能够申请胜利的,是因为咱们没有被动调用中断办法。

undici.request('http://127.0.0.1:3100', {  method: 'GET',  signal: abortController.signal,}).then(({ statusCode, body }) => {  console.log('申请胜利')  body.on('data', (data) => {    console.log(statusCode, data.toString())  })}).catch(error => {  // 捕捉因为中断触发的谬误  console.log('error', error.name)})// 调用中断abortController.abort()

当初运行代码会发现,并没有输入 申请胜利 的日志,进入了 catch 逻辑,胜利的进行了申请的中断。

undici.steam

undici.steam 办法能够用来进行文件下载,或者接口代理。

文件下载

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

接口代理

const http = require('http')const undici = require('undici')// 将 3100 端口的申请,代理到 80 端口const client = new undici.Client('http://localhost')http.createServer((req, res) => {  const { url, method } = req  client.stream(    { method, path: url,opaque: res },    ({ opaque }) => opaque  )}).listen(3100)

总结

本文只是介绍了 undici 几个 api 的应用形式,看起来 undici 上手难道还是比拟低的。然而兼容性还不太行,比方,fetch 只反对 node@v16.5.0 以上的版本。

对于这种比拟新的库,集体还是倡议多张望一段时间,尽管 request 曾经废除了,咱们还是应用一些通过较长时间考验过的库,比方,egg 框架中应用的 urllib,还有一个 node-fetch,上手难道也比拟低,与浏览器中的 fetch api 应用形式统一。