Resend body from response exactly as it comes

2019-07-23 19:57发布

问题:

I'm using a 3rd party API Rest which returns the contents of a file in the body. This file can be text or binary (pdf, docx).

For security reasons I need to use an intermediate API Rest as a bridge between my frontend app and this 3rd party API Rest.

What I want is to be able to return the exact same body that I get from the 3rd party to my frontend app, because at the moment as I get the body and build a new response in my intermediate API I'm somehow modifying something.

This is what I do in my intermediate API:

const options = {
  method: 'GET',
  uri: `${api}`,
  headers: { OTCSTICKET: ticket}
}

rp(options)
  .then(parsedBody => res.status(201).send(parsedBody))
  .catch(err => res.status(400).send({ msg: 'download error', err }));

I would need to send exactly the same body that I get in the response. How can I do that?

Thanks

回答1:

Ok I managed to get this working, so I'll post here in case it helps someone.

This thread gave me the solution Getting binary content in Node.js using request

So I just set the encoding to null and I passed as body the one I got from the 3rd party API

const options = {
  method: 'GET',
  uri: `${api}`,
  headers: { OTCSTICKET: ticket},
  encoding: null,
  resolveWithFullResponse: true
}

rp(options)
  .then(response => res.status(201).send(response.body))
  .catch(err => res.status(400).send({ msg: 'download error', err }));

With this I managed to get this working.