在 Node.js 中使用 Undici 的 Fetch API
🌐 Using the Fetch API with Undici in Node.js
介绍
🌐 Introduction
Undici 是一个 HTTP 客户端库,为 Node.js 中的 fetch API 提供支持。它是从零开始编写的,不依赖于 Node.js 内置的 HTTP 客户端。它包含许多功能,使其成为高性能应用的理想选择。
有关 Undici 规范遵从性的信息,请参阅 Undici 文档。
🌐 For information on Undici's specification compliance, see the Undici documentation.
基本 GET 用法
🌐 Basic GET Usage
async function () {
// Like the browser fetch API, the default method is GET
const = await ('https://jsonplaceholder.typicode.com/posts');
const = await .();
.();
// returns something like:
// {
// userId: 1,
// id: 1,
// title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
// body: 'quia et suscipit\n' +
// 'suscipit recusandae consequuntur expedita et cum\n' +
// 'reprehenderit molestiae ut ut quas totam\n' +
// 'nostrum rerum est autem sunt rem eveniet architecto'
// }
}
().(.);
基本 POST 用法
🌐 Basic POST Usage
// Data sent from the client to the server
const = {
: 'foo',
: 'bar',
: 1,
};
async function () {
const = await ('https://jsonplaceholder.typicode.com/posts', {
: 'POST',
: {
'User-Agent': 'undici-stream-example',
'Content-Type': 'application/json',
},
: .(),
});
const = await .();
.();
// returns something like:
// { title: 'foo', body: 'bar', userId: 1, id: 101 }
}
().(.);
使用 Undici 自定义 Fetch API
🌐 Customizing the Fetch API with Undici
Undici 允许你通过向 fetch 函数提供选项来自定义 Fetch API。例如,你可以设置自定义头部、设置请求方法以及设置请求主体。以下是使用 Undici 自定义 Fetch API 的示例:
🌐 Undici allows you to customize the Fetch API by providing options to the fetch function. For example, you can set custom headers, set the request method, and set the request body. Here is an example of how you can customize the Fetch API with Undici:
fetch 函数接受两个参数:要获取的 URL 和一个选项对象。选项对象是 Request 对象,你可以用它来自定义请求。该函数返回一个 Promise,该 Promise 解析为一个 Response 对象。
🌐 The fetch function takes two arguments: the URL to fetch and an options object. The options object is the Request object that you can use to customize the request. The function returns a Promises that resolves to a Response object.
在以下示例中,我们向 Ollama API 发送一个带有 JSON 负载的 POST 请求。Ollama 是一个 CLI 工具,允许你在本地机器上运行大型语言模型 (LLM)。你可以在 这里 下载它。
🌐 In the following example, we are sending a POST request to the Ollama API with a JSON payload. Ollama is a cli tool that allows you to run LLM's (Large Language Models) on your local machine. You can download it here
ollama run mistral
这将下载 mistral 模型并在你的本地机器上运行它。
🌐 This will download the mistral model and run it on your local machine.
通过使用连接池,你可以重复使用与同一服务器的连接,这可以提高性能。以下是如何在 Undici 中使用连接池的示例:
🌐 With a pool, you can reuse connections to the same server, which can improve performance. Here is an example of how you can use a pool with Undici:
import { } from 'undici';
const = new ('http://localhost:11434', {
: 10,
});
/**
* Stream the completion of a prompt using the Ollama API.
* @param {string} prompt - The prompt to complete.
* @link https://github.com/ollama/ollama/blob/main/docs/api.md
**/
async function () {
const { , } = await .request({
: '/api/generate',
: 'POST',
: {
'Content-Type': 'application/json',
},
: .({ , : 'mistral' }),
});
// You can read about HTTP status codes here: https://web.nodejs.cn/en-US/docs/Web/HTTP/Status
// 200 means the request was successful.
if ( !== 200) {
// consuming the response body is mandatory: https://undici.nodejs.org/#/?id=garbage-collection
await .dump();
throw new (`Ollama request failed with status ${}`);
}
let = '';
const = new ();
for await (const of ) {
+= .(, { : true });
.();
}
.('Streaming complete.');
}
try {
await ('What is recursion?');
} catch () {
.('Error calling Ollama:', );
} finally {
.('Closing Ollama pool.');
.close();
}
使用 Undici 流式响应
🌐 Streaming Responses with Undici
Streams 是 Node.js 中的一个功能,它允许你读取和写入数据块。
import { } from 'node:stream';
import { } from 'undici';
async function () {
const = 'https://api.github.com/users/nodejs/repos';
await (
,
{
: 'GET',
: {
'User-Agent': 'undici-stream-example',
: 'application/json',
},
},
=> {
let = '';
return new ({
(, , ) {
+= .toString();
();
},
() {
try {
const = .();
.(
'Repository Names:',
.map( => .name)
);
} catch () {
.('Error parsing JSON:', );
}
.('Stream processing completed.');
.(`Response status: ${.statusCode}`);
();
},
});
}
);
}
().(.);