Wednesday 3 May 2017

Returning a different response object in express.js

I'm trying to port a proxy feature that is used for debugging purposes from a hapi.js server to an express.js server.

The feature uses the https module to retrieve data from a different server and I want to simply forward the response from this retrieval to the original client.

Simplified code:

server.get('/proxy/*', (req, res) => {
  https.request({
    protocol: 'https:',
    hostname: 'example.com',
    path: req.url.replace(/^\/proxy\//, ''),
    headers: Object.assign({}, req.headers)
  }, (proxiedResponse) => {
    // respond with proxiedResponse here somehow
  });
});

In Hapi, I could do this easily with reply(proxiedResponse); (reply is Hapi's counterpart to res) since reply isn't an actual response object but a function that internally creates and dispatches a response.
Since in Express, res is the actual response object I guess I need to replace/mod it somehow.

Is there a way to do this in an easier way than to explicitly copy every relevant piece of data from proxiedResponse into res?



via Mikael Lennholm

No comments:

Post a Comment