preface
In the browser, we used to use XHR if we wanted to make a request, but the underlying API was often called in a crude way. JQuery’s $. Ajax was probably the best choice for efficiency, but a more modern FETCH API has since come along.
However, considering the compatibility of FETCH and the fact that it does not support some global configurations and request interrupts, we may use the AXIOS request library to make some requests in actual use. In Node.js, almost all requests are made through the request library. Unfortunately, Request went out of maintenance two years ago, and it’s not easy to find a replacement library in Node.js.
In the request issues section, there is a table that recommends some common request libraries in Node.js:
The package name | Packet size | API style | Introduction to the |
---|---|---|---|
node-fetch | 0.4 KB | promise / stream | A light-weight module that brings window.fetch to Node.js |
got | 48.4 KB | promise / stream | Simplified HTTP requests |
axios | 11.9 KB | promise / stream | Promise based HTTP client for the browser and node.js |
superagent | 18kb | chaining / promise | Small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features |
urllib | 816kb | callback / promise | Help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more. |
Axios, which is used a lot in browsers, doesn’t work well in Node.js, especially when it comes to uploading files, which can cause unexpected problems.
Recently, when I was online at 🏄🏿, I found that Node.js officially has a request library called Undici, which is quite complicated to obtain. So, today’s article will introduce undici. By the way, undici is the meaning of Italian 11, as if double eleven is coming soon, good Maotai 🤔.
Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. It is also a Stranger Things reference.
Get started
We can install undici directly via NPM:
npm install undici -S
Copy the code
Undici exposes an object that provides several apis:
undici.fetch
: initiates a request, and the browserfetch
Method consistency;undici.request
: Initiate a request, andrequest
The library is similar in that this method supports Promise;undici.stream
: Handle file stream, can be used for file download;
undici.fetch
Note: This method requires Node version >= V16.5.0
Before requesting the service through Undici.fetch, you need to start a simple login service through 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)
Copy the code
The above code is very simple and only supports accepting a POST method to /login route. Let’s use Undici.fetch to make a POST request.
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, 'Request failed')
return
}
const json = await rsp.json()
console.log(rsp.status, json)
}
bootstrap()
Copy the code
If you change the request to GET, a 404 is returned.
const rsp = await fetch(api, {
method: 'GET'
})
Copy the code
undici.request
Undici. Request is called in a similar way to Undici. Fetch, and its parameter form is similar.
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()
Copy the code
The request method returns the HTTP response in the body property, which also supports methods like.json()/.text().
Interrupt request
Install the abort controller library, and then instantiate abort Controller to pass the interrupt signal into the Request configuration.
npm i abort-controller
Copy the code
const undici = require('undici')
const AbortController = require('abort-controller')
// Instantiate abort-controller
const abortController = new AbortController()
undici.request('http://127.0.0.1:3100', {
method: 'GET'.// Incoming interrupt semaphore
signal: abortController.signal,
}).then(({ statusCode, body }) = > {
body.on('data'.(data) = > {
console.log(statusCode, data.toString())
})
})
Copy the code
We run the code and find that we can request success because we didn’t actively call the interrupt method.
undici.request('http://127.0.0.1:3100', {
method: 'GET'.signal: abortController.signal,
}).then(({ statusCode, body }) = > {
console.log('Request successful')
body.on('data'.(data) = > {
console.log(statusCode, data.toString())
})
}).catch(error= > {
// Catch an error triggered by an interrupt
console.log('error', error.name)
})
// Call interrupt
abortController.abort()
Copy the code
Now when you run the code, instead of logging the success of the request, you enter the catch logic and interrupt the request successfully.
undici.steam
The undici. Steam method can be used for file downloads, or interface proxies.
File download
const fs = require('fs')const { stream } = require('undici')const out = fs.createWriteStream('./ Song Dynasty - Ge Yao - Gold Wire and Iron Wire. JPG ')const url = 'https://img.dpm.org.cn/Uploads/Picture/dc/cegift/cegift6389.jpg'stream(url, { opaque: out }, ({ opaque }) = > opaque)
Copy the code
The interface agent
const http = require('http')const undici = require('undici')// The request for port 3100, 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)
Copy the code
conclusion
This article only introduces the use of several APIS of Undici, it seems that undici is relatively low. However, compatibility is not very good, for example, fetch only supports versions above [email protected].
Although Request has been deprecated, we still use some long-tested libraries, such as urllib used in egg framework, and node-fetch. The fetch API is used in the same way as in the browser.