Node.js Express -代理请求后调用next()

Node.js Express - calling next() after proxying the request

本文关键字:调用 next 请求 js Express 代理 Node      更新时间:2023-09-26

我正在编写Express.js应用程序,它应该将请求路由到某个代理服务器,作为管道中的最后一步。我使用了http-proxy代理库,因为它支持websockets。问题是,我需要在请求被重定向后继续使用我的应用程序,以便收集一些我将用于日志记录的信息(api调用的响应时间等)。这个想法是在请求被代理后调用next()函数,这应该返回到堆栈中的第一个中间件?(如果我写错了请指正)然后计算起始点和当前点的时差

在调用proxy.web(req, res, {target: serviceAddress});next()之后-我得到错误:

_http_outgoing.js:335
    throw new Error('Can''t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at d:'WebStorm Projects'api-gateway'node_modules'http-proxy'lib'http-proxy'passes'web-outgoing.js:85:11
    at Array.forEach (native)
    at Array.writeHeaders (d:'WebStorm Projects'api-gateway'node_modules'http-proxy'lib'http-proxy'passes'web-outgoing.js:84:35)
    at ClientRequest.<anonymous> (d:'WebStorm Projects'api-gateway'node_modules'http-proxy'lib'http-proxy'passes'web-incoming.js:149:20)
    at ClientRequest.emit (events.js:107:17)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:426:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
    at Socket.socketOnData (_http_client.js:317:20)
    at Socket.emit (events.js:107:17)

是否有一个解决方案,保持工作后proxy.web(...)被调用?或者如果我的方法是错误的,谁能建议我一个解决方案吗?

您不应该在发送响应后调用next(),因为您主动不希望剩余的中间件(它也将尝试发送响应)运行。

相反,您应该把所有的日志中间件放在前面。