3

I have User Register page which is built with ExpressJS. The data entered here by the user should be passed over to an external Api (Java Rest Api). But I am not getting the JSON data at the receiving end. Also I have to send the response only after creating the User. Below are the code snippets:

Here is my ExpressJS code: (I am using Postman app to post the JSON data here)

router.post('/register', function(req, res, next) {
  console.log(req.body);  // JSON sent from Postman is showing correctly

  var options = {
      method: 'POST',
      uri: 'http://localhost:3000/userCreation',
      body: req.body,
      json: true,
      headers: { 'Content-Type': 'application/json' }
  }
  // Here rp is require('request-promise');
  rp(options).then(function (res){
      console.log("Response from external Api: "+res);
  })
  .catch(function (err) {
      console.log(err);
  })
  // The response below should be ideally sent after the User Registration is done. 
  // So it should go into the "then" block. But I am an unable to put it there.
  // It says "cannot send header twice"
  res.send('Json Data sent to Java/MongoDB & User Created successfully.');

});

This is the code at the receiving end (Java API - but for now, I have another ExpressJS app to test the flow):

router.post('/userCreation', function(req, res, next) {
  console.log("User registration in MongoDB");
  console.log(req.hostname);  // O/p : localhost
  console.log(req.body);      // O/p : undefined
  res.send("User successfully created in MongoDB");
});

Any help/suggestion on this would be really helpful. Thanks in advance.

2
  • You say you are using json, but send back text. Use res.json I guess. Commented Aug 28, 2017 at 12:46
  • Yes, you are right - I need to change that. But the actual problem lies before that in "rp(options)" statement. Here the options include a body with JSON data, which is not received at the other end. Commented Aug 29, 2017 at 3:46

1 Answer 1

1

I got the answer..... "app.use(bodyParser.json())" was required at both the instances of the ExpressJS server. Now it is working fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.