使用express&在服务器端解析AngularJS http.post数据;正文解析器
Parsing AngularJS http.post data on server side with express & body-parser
我最近刚开始学习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。
相关文章:
- 如何从HTTP上下文对象中获取Post数据
- 如何绑定“;这个“;在$http.post中->在AngularJS中解析/拒绝?(现在this=Window对象
- Angular JS `$http`发送POST而不是GET
- 为什么我的$http.post返回一个400错误
- AngularJS$http.post调用返回502(坏网关)错误
- 如何处理HTTP 204”;无内容”;在Restangular POST中
- AngularJS$http.post没有'不适用于Chrome,仅适用于IE
- 如何将多个onError函数分配给promise(由angular's$http.post返回)
- 如何将AJAX POST转换为HTTP POST,以便在单击时发布
- $http.post undefined 不是函数
- 在Selenium IDE中执行HTTP POST
- 从 Angular 数据工厂中的 HTTP POST 请求接收未定义的结果
- $http.post() angularjs 响应函数未按正确的顺序执行
- AngularJS:POST $http意外标识符
- 如何在 NodeJS 中传递响应参数,包括来自 POST http.request 的正文
- AngularJS在POST http请求上更新模型/视图
- 如何将dropbox API v2 POST HTTP请求转换为jQuery$.ajax
- 无法运行内部功能测试.错误:[POST http://localhost:4444/wd/hub/session] co
- JavaScript可以向任何域发送POST HTTP请求吗?
- POST http://localhost:51348/TestService.svc/SendCredentials