Node.js 如何使用axios转发节点请求?

Node.js 如何使用axios转发节点请求?,node.js,express,proxy,axios,request,Node.js,Express,Proxy,Axios,Request,在我的express.js服务器中,我这样做是为了将请求转发到另一台服务器 async handleRequest(req, res) { const serverUrl = "http://localhost:4000" await req.pipe(request({ url: serverUrl + req.url })).pipe(res); } 这是预期的工作。 但我决定使用axios或got库来代替请求,因为请求已不再维护。 但这样的事情是行不

在我的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)

我怎样才能解决这个问题?我希望在不更改请求对象的情况下按原样转发请求。

您需要使用
responseType
参数和值
stream
,因此axios允许您通过以下方式将响应数据作为流进行管道传输:

axiosResponse.data.pipe(destination); // where destination can be a file or another stream
此外,实际上不需要执行
wait req.pipe
,因为axios会将响应流式传输到您的express response(res)对象中

因此,答案是完整的:

  const axiosResponse = await axios({
    url: serverUrl + req.url,
    responseType: 'stream'
  })

  axiosResponse.data.pipe(res)

如何从“请求”导入请求刚刚添加了一个答案,希望对您有所帮助