我有用户注册页面,它是用ExpressJS构建的 . 用户在此输入的数据应传递给外部Api(Java Rest Api) . 但我没有在接收端获得JSON数据 . 此外,我必须在创建用户后才发送响应 . 以下是代码段:
这是我的ExpressJS代码:(我使用Postman应用程序在这里发布JSON数据)
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.');
});
这是接收端的代码(Java API - 但是现在,我有另一个ExpressJS应用程序来测试流程):
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");
});
任何关于此的帮助/建议都会非常有帮助 . 提前致谢 .
1 回答
我得到了答案......“app.use(bodyParser.json())”在ExpressJS服务器的两个实例都是必需的 . 现在它工作正常 .