0

I have a call made from my client that passes in some post data like this:

function doSomethingApi(email) {
  return axios({
    method: 'post',
    url: `/api`,
    data: {
      scan_refference: 'ref',
      user_email: email
    }
  })
}

On the server side this gets proxied to apply certain secrets:

app.post('/api', (req, res) => {
  const url = 'https://my.api.com';
  req.pipe(request({
    url,
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    auth: {
      user: secrets.USERNAME,
      pass: secrets.PASSWORD
    },
    body: {
      value1: `${secrets.VALUE1}`,
      value2: `${secrets.VALUE2}`
    }
  })).pipe(res);
});

request and axios are just 2 different http libraries I use, one is preferred for client other for server, thats all. Issue now is that I am overwriting body in my proxy, where as I want to simply add value1 and value2 to existing body passed from client.

Ilja
  • 44,142
  • 92
  • 275
  • 498

1 Answers1

1

First get the body from the initial call as a JSON object. This depends on what you use, but e.g. in Express you could:

app.use(express.bodyParser());

Then

var previousBody = req.body

Finally merge the initial JSON with whatever you want (NOTE: this means your client will definitely not be able to use the "value1" and "value2" properties, because they will be overwritten)

body: Object.assign(previousBody, {
  value1: `${secrets.VALUE1}`,
  value2: `${secrets.VALUE2}`
})
Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30
  • Adding body parser to the project hangs api calls, they never update from pending state and time out eventually – Ilja Dec 07 '16 at 12:46
  • Then could you do it manually http://stackoverflow.com/questions/6486208/node-js-parse-json-object ? Just make sure the proxy only passes on the end event from the initial request. – Ovidiu Dolha Dec 07 '16 at 12:57
  • Alright I managed to get req.body working and fixed bodyParser issue, however, now once I add body param in my request options I get `write after end` error from express – Ilja Dec 07 '16 at 13:22
  • it's hard to know exactly how the code looks now... but could this help - https://github.com/request/request/issues/1664 ? – Ovidiu Dolha Dec 07 '16 at 13:28
  • they are also using pipe-ing which i think causes the problem, and fixing it like: – Ovidiu Dolha Dec 07 '16 at 13:29
  • app.use('/', (req, res) => { req.pipe(request.post({ url: 'http://www.example.com', form: { foo: 'bar' }}), {end: false}).pipe(res); }); --- (note the {end: false} stuff ) – Ovidiu Dolha Dec 07 '16 at 13:29