我正在制作一个 angular2/Node.js 应用程序。现在,当我尝试从 Node 服务器获取对象时,它返回得很好。但是,当我尝试将数据发布到 Node 服务器时。 request.body 显示未定义。我究竟做错了什么 ?
服务器.js
// Test
router.get('/test', function (req, res) {
res.json({test:true}); // Works
});
// Post
router.post('/rest', function (req, res) {
var body = req.body;
console.log(body); // Undefined
res.json({test:true});
});
app.ts
constructor(private http:Http){
console.log("Test")
http.get('/api/User/test').subscribe(result => {
console.log(result.json());
});
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post('/api/User/rest',{test:'Testing req'},{headers:headers})
.subscribe(result => {
console.log(result.json());
});
}
最佳答案
你安装了body-parser吗?
npm install body-parser --save
在您的路线之前,将其添加到您的快速应用程序中
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
关于javascript - Node - Post 请求显示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399960/