在 Node.js 中,pipe 是一个非常有用的方法,它用于在可读流和可写流之间建立管道,从而实现数据的传输。在上下文中,可读流通常是从一个数据源(比如网络请求、文件读取等)获取数据,而可写流则是将数据写入到目标(比如网络响应、文件写入等)。

在示例中,response.data.pipe(res) 的作用是将来自 Axios 请求的响应数据流(可读流)传递给 Express 响应对象(可写流),这样就可以直接将来自目标服务器的响应数据流传递给客户端,而无需将整个响应数据存储在内存中。

使用 pipe 方法可以大大简化数据传输的过程,并且在处理大量数据时能够有效地减少内存占用。

javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const express = require("express");
const axios = require("axios");
const app = express();

app.get("/forward", async (req, res) => {
try {
const response = await axios.get("目标服务器的URL", {
headers: {
// 设置需要转发的请求头
Authorization: "Bearer token",
},
responseType: "stream", // 指定响应数据的类型为流
});

// 设置转发的响应头
res.set({
"Content-Disposition": response.headers["content-disposition"],
"Content-Length": response.headers["content-length"],
"Content-Type": response.headers["content-type"],
});

// 将目标服务器的响应数据转发给客户端
response.data.pipe(res);
} catch (error) {
console.error(error);
res.status(500).send("Proxy Request Failed");
}
});

app.listen(3000, () => {
console.log("Server is running on port 3000");
});

在上面的示例中,当你访问 /forward 路由时,Express 将使用 Axios 发起一个请求到目标服务器,并将目标服务器的响应直接转发给客户端。需要将 目标服务器的URL 替换为实际的目标服务器 URL。同时,通过设置 responseType: 'stream',我们告诉 Axios 响应数据的类型为流,这样可以直接将数据流传递给客户端。