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

标签 javascript node.js express http-proxy

我正在编写 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(),因为您主动不想剩下的中间件(它也会尝试发送响应)到跑。

相反,您应该首先放置所有日志记录中间件。

关于javascript - Node.js Express - 在代理请求后调用 next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32380010/

相关文章:

javascript - 是否可以防止修改对象的特定键值?

javascript - Grunt 通知未运行

python - Plotly:如何使用 plotly express 在辅助 y 轴上绘图

javascript - WebStorm 中的代码补全就像 ReSharper for Visual Studio 一样

javascript - 使用 R 在搜索后面抓取 asp javascript 分页表

javascript - 由路由器中的 html webpack 插件生成的渲染文件

node.js - 如何在 Node 中处理url+多个可选查询参数?

正则表达式帮助 - Express 路由 url

javascript - 从同一个 node.js 子进程运行多个命令

javascript - jQuery 元素字符串数组