Node-http-proxy: change response if proxy response is 5xx

Created on 27 Feb 2016  路  7Comments  路  Source: http-party/node-http-proxy

I cant modify response if proxy response is 5xx.

proxy.on('proxyRes', function (proxyRes, req, res) {
  if (req.method === 'GET' && (proxyRes.statusCode >= 500 || proxyRes.statusCode <= 599)) {
    let cacheContent = getCacheContent(req);
    res.writeHead(cacheContent.statusCode, cacheContent.headers);
    res.write(cacheContent.buffer);
    res.end();
  }
});

It's give me an error:

_http_outgoing.js:344
    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:344:11)
    at /home/sweb/prj/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js:86:13
    at Array.forEach (native)
    at Array.writeHeaders (/home/sweb/prj/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js:84:35)
    at ClientRequest.<anonymous> (/home/sweb/prj/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:150:20)

Most helpful comment

I thinks it's must be major use cases for failover proxy server. why no attention ?

All 7 comments

I thinks it's must be major use cases for failover proxy server. why no attention ?

+1

+1

+1

+1

I have the same problem

        // watch the event from the proxy , if the resule is 404 
        this.proxy.on('proxyRes',  (proxyRes, req, res) =>{
            if (proxyRes.statusCode == 404){
                let baseUrl : string = req.baseUrl;
                let regexp = /^(.*)\/u-dyn\/sync\.js\/?(?=\/|$)/i;
                if (baseUrl.match(regexp)){
                    this.logger.info(`the proxy is not avalible ,so will load the i18n Info from local`);
                    this.provideI18NInfo(res);
                }
            }
        });
       this.proxy.web(req, res, {target: this.proxyUrl, proxyTimeout : 2000},error =>{})

Use the following method posted here Worked great for me!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guillaume-at-palo picture guillaume-at-palo  路  4Comments

miton18 picture miton18  路  5Comments

mohammad-goldast picture mohammad-goldast  路  3Comments

jnjnljljjsw picture jnjnljljjsw  路  6Comments

robertjchristian picture robertjchristian  路  6Comments