简体   繁体   中英

How can I pass a proxied response when 'selfHandleResponse' is true?

I am running a development proxy-server where on startup I make a request for an auth token with our cluster architecture.

However, this token expires after some time. Then instead of the developer restarting their proxy-server, I would like to make another request to get another valid auth token. To be able to handle the response by myself I set the node-http-proxy option selfHandleResponse to true.

app.use(
  '/',
  index({
    target: config.hostname,
    changeOrigin: true,
    onProxyReq,
    onProxyRes,
    selfHandleResponse: true
  })
);

Now, I only want to handle responses with a 401 , because it is the only case I need to request another token.

const onProxyRes = (proxyRes, req, res) => {
  if (proxyRes.statusCode === 401) {
    getToken()
      .then(forwardRequest(req))
      .then((response) => {
        res.send(response.body);
      })
      .catch(() => {        
        res.sendStatus(500);
      });
  }

  // How to pass back the original proxyRes including body, headers etc.?
});

EDIT: forwardRequest is my function to retry the original request and then hand it back to the client when successful.

My trouble starts here, since I have no idea on how to pass the proxied non-401 request back to the client. I found myself starting to implement body parsing logic dependent on header content-type, but I very much hope there is an easier way.

Any ideas?

The solution is simple...

proxyRes.pipe(res);

Found in the source code of node-http-proxy .

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