Reputation: 3987
Im making a angular2/Node.js application. Right now when i try to get a object from the node server, it returns just fine. However, when i try to post data to the node server. The request.body shows undefined. What am i doing wrong ?
server.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());
});
}
Upvotes: 0
Views: 1642
Reputation: 3497
Did you install body-parser?
npm install body-parser --save
and before your routes, add it to your express application
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
see also: https://github.com/expressjs/body-parser
Upvotes: 2