我最近刚开始学习MEAN堆栈,所以如果这是一个非常愚蠢的问题,请原谅我。我的问题如下:
在客户端(controller.js),我有
$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
}
})
在服务器端,我有
app.post('/root', function(req, res) {
console.log(req.body);
console.log(req.body.username);
});
我的控制台日志显示:
17 Nov 21:39:04 - [nodemon] starting `node server/server.js`
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
undefined
我想req.body.username会给我testUserName,但我没有定义。我得到的JSON格式有点奇怪。有人能帮我解决这个问题吗?我做了一些阅读,并尝试使用body解析器,浏览了angular js$http.post文档,但没有找到任何能帮助我的东西。
我想问题出在:
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
但我似乎不知道如何在我的角度控制器中传递来自$http.post的数据,这样我就只能得到标识符:值格式的请求。
无论如何,我都想明白了。似乎我需要从编码中休息一下。
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
至
headers : { 'Content-Type': 'application/json' }
解决了问题。
试试下面的源代码:
$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('&');
}
})
$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
}
})
用"params"试试,也许它不起作用,但试试:p
我尝试过使用"params"而不是"data",并且工作正常,无论标题是"application/x-www-form-urlencoded"还是"application/json"但使用"application/json"可以在节点上使用request.query.param1。