简体   繁体   English

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

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

I'm writing the Express.js application, which should route the request to some proxy server as a last step in the pipeline. 我正在编写Express.js应用程序,该应用程序会将请求路由到某些代理服务器,作为管道的最后一步。 I've used http-proxy proxying library, since it supports websockets. 我使用了http-proxy代理库,因为它支持websockets。 The problem is that I need to continue working with my application after the request is redirected, so as to collect some info which I'll be using for logging (response time for api call etc.). 问题是重定向请求后,我需要继续使用我的应用程序,以便收集一些我将用于记录日志的信息(api调用的响应时间等)。 The idea was to call next() function after request is proxied, which should return me to the first middleware in the stack?(please correct me if I'm wrong) and then calculate the time difference between the starting point and the current one. 这个想法是在请求被代理后调用next()函数,这应该使我返回到堆栈中的第一个中间件?(如果我错了,请更正我),然后计算起点和当前点之间的时间差。

After calling proxy.web(req, res, {target: serviceAddress}); 调用proxy.web(req, res, {target: serviceAddress}); and next() right after it - I get the error: 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) 

Is there a solution for keeping working after proxy.web(...) is called? 调用proxy.web(...)之后,有解决方案可以保持工作吗? Or in case my approach is wrong, could anyone suggest me a solution for this? 还是万一我的方法是错误的,有人可以建议我解决这个问题吗?

You should not call next() after sending a response, since you actively don't want the remaining middleware (which will also try to send a response) to run. 发送响应后,不应调用next() ,因为您实际上不希望其余的中间件(也将尝试发送响应)运行。

Instead, you should put all of your logging middleware first. 相反,您应该将所有日志记录中间件放在首位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM