简体   繁体   中英

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. I've used http-proxy proxying library, since it supports 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.). 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.

After calling proxy.web(req, res, {target: serviceAddress}); and next() right after it - I get the error:

 _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? 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.

Instead, you should put all of your logging middleware first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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