Reputation: 59
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.
Upvotes: 3
Views: 610
Reputation: 59
I got the answer..... "app.use(bodyParser.json())" was required at both the instances of the ExpressJS server. Now it is working fine.
Upvotes: 1