Reputation:
I just recently started learning MEAN stack so forgive me if this seems like a really dumb question. My problem is as follows:
On the client side (controller.js) I have,
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
data : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
}
})
On the server side I have,
app.post('/root', function(req, res) {
console.log(req.body);
console.log(req.body.username);
});
My console log shows:
17 Nov 21:39:04 - [nodemon] starting `node server/server.js`
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
undefined
I would imagine req.body.username to give me testUserName but I get undefined. The JSON format I am getting is slightly weird. Can anyone help me out this one? I did some reading and tried using body-parser and went through angular js $http.post documentation but didn't find anything that would help me out.
I imagine the problem is at:
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
but I cant seem to figure out how I would pass the data from $http.post in my angular controller so that I would just get my request in identifier:value format.
Upvotes: 2
Views: 2653
Reputation: 51
I've tried with "params" instead of "data" and worked ok, and doesn't matter if headers are "application/x-www-form-urlencoded" or "application/json" But using "application/json" works with request.query.param1 on node.
Upvotes: 0
Reputation: 5376
Try my source code below:
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
data : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
},
transformRequest: function(obj) {
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
return str.join('&');
}
})
Upvotes: 1
Reputation:
Nevermind, I figured it out. Seems like I needed a break from coding.
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
to
headers : { 'Content-Type': 'application/json' }
fixed the problem.
Upvotes: 2
Reputation: 39
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
params : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
}
})
try it with 'params', maybe it won't work but try it :P
Upvotes: 0