Undici: A Fast HTTP Client for Node.js
Undici is a powerful and efficient HTTP/1.1 client designed for Node.js. Named after the Italian word for eleven, “undici” is built to handle modern web applications with performance in mind. Below, we introduce dozens of useful APIs provided by the Undici library, complete with code snippets to showcase their functionality.
Getting Started with Undici
To start using Undici, you first need to install it via npm:
npm install undici
Once installed, you can import it into your Node.js application:
const { request, Pool, Client } = require('undici');
Basic Request
Performing a basic HTTP GET request with Undici is straightforward:
const { request } = require('undici');
async function fetchData() {
const response = await request('https://api.example.com/data');
const data = await response.body.json();
console.log(data);
}
fetchData();
Advanced Request Options
Undici allows for more advanced request configurations:
async function fetchData() {
const response = await request('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ key: 'value' }),
headers: { 'Content-Type': 'application/json' }
});
const data = await response.body.json();
console.log(data);
}
fetchData();
Using Pool
Manage multiple requests using the Pool API:
const { Pool } = require('undici');
const pool = new Pool('https://api.example.com');
async function fetchData() {
const response = await pool.request({
path: '/data',
method: 'GET'
});
const data = await response.body.json();
console.log(data);
}
fetchData();
Using Client
For more control over the requests, you can use the Client API:
const { Client } = require('undici');
const client = new Client('https://api.example.com');
async function fetchData() {
const response = await client.request({
path: '/data',
method: 'GET'
});
const data = await response.body.json();
console.log(data);
}
fetchData();
App Example
Let’s create an example application using the above APIs to fetch and display data from an API:
const { Pool, Client } = require('undici');
const express = require('express');
const app = express();
const pool = new Pool('https://api.example.com');
app.get('/data', async (req, res) => {
try {
const response = await pool.request({ path: '/data', method: 'GET' });
const data = await response.body.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Something went wrong' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This app uses express to create a simple server that responds with data fetched from an external API using the Undici pool API.
Hash: 9043402da0ddf12f45b1a71e6925019336c448f3e11e5601d1bfdde8f338a463