在我的 express.js 服务器中,我这样做是为了将请求转发到另一台服务器
async handleRequest(req, res) {
const serverUrl = "http://localhost:4000"
await req.pipe(request({ url: serverUrl + req.url })).pipe(res);
}
这是按预期工作的。
但我决定使用 axios
或 got
库而不是请求,因为不再维护请求。
但是这样的事情是行不通的 -
req.pipe(axios({url: serverUrl + req.url})).pipe(res);
我收到错误
(node:88124) UnhandledPromiseRejectionWarning: TypeError: dest.on is not a function
at IncomingMessage.Readable.pipe (internal/streams/readable.js:671:8)
我该如何解决这个问题?我想按原样转发请求,而不对请求对象进行任何更改。
答案 0 :(得分:1)
您需要使用值为 responseType
的 stream
参数,因此 axios 为您提供了将响应数据作为流传输的选项:
axiosResponse.data.pipe(destination); // where destination can be a file or another stream
此外,实际上没有必要做 await req.pipe
因为 axios 会将响应流式传输到您的快速响应 (res) 对象中
因此是完整的答案:
const axiosResponse = await axios({
url: serverUrl + req.url,
responseType: 'stream'
})
axiosResponse.data.pipe(res)