Reputation: 530
I am using nodejs as back-end for angular 5 application . When I am posting data with http post request then it coming at nodejs in wrong formate (Values as property)- This is my service code of angular 5 -
login(email: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = { EmailAddress: email, Password: password };
return this.http.post('http://localhost:3000/api/user/login', body, options )
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
This is Node API - in body I am getting value as property
app.post('/api/user/login', urlencodedBodyparser, function (req, res) {
console.log(req.body);
User.find({ "EmailAddress": req.body["EmailAddress"], "Password": req.body["Password"] }, function (err, users) {
console.log(users.length);
if (err != null) {
sendError(err, res);
}
if (users != null) {
var count = users.length;
if (count > 0) {
response.data = users[0];
res.json(response);
}
else {
sendError({ message :'No user found'}, res);
console.log("Login Failed");
}
}
else {
sendError(err, res);
}
})
});
Code for body parser -
var bodyParser = require('body-parser');
var urlencodedBodyparser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedBodyparser);
Upvotes: 0
Views: 449
Reputation: 551
You need to use body-parser middleware https://github.com/expressjs/body-parser
Here is more information What does body-parser do with express?
Try to use this :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
Upvotes: 1
Reputation: 309
try to change the header content-type to json
application/json
like this:
options() {
const headers = new Headers({
'content-type': 'application/json'
});
const options = new RequestOptions({ headers: headers });
return options;
}
login(): Observable<any> {
return this.http.post('http://localhost:3000/api/user/login', this.options()).
map((res: Response) => res.json());
}
Upvotes: 2