[英]Can't get POST data in NodeJS from Angular app
I can't get the params from a POST method I made from an Angular app. 我无法从Angular应用程序制作的POST方法中获取参数。 I tried looking for an answer here and even copy/paste some examples but nothing seems to work. 我试图在这里寻找答案,甚至复制/粘贴一些示例,但似乎无济于事。
The Node code: 节点代码:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public_html'));
app.post('/test', function (request, response) {
console.log(request.body.name)
response.status(201).json(request.body.name);
});
app.listen(8787,function() {
console.log('Listening on 8787');
});
The Angular code: 角度代码:
$scope.postData = function() { $ scope.postData = function(){
$http.post('/test',{name: $scope.name}).success(function(data,status) {
console.log('SUCCESS: ' + status);
console.log(data);
}).error(function(error) {
console.log('ERROR');
console.log(data);
})
}
I can see on the network panel of the developer tools that the data is sent and I even get the http code of 201 as expected but I'm not getting back the reply. 我可以在开发人员工具的网络面板上看到已经发送了数据,而且我什至得到了201的http代码,但没有得到答复。 In the console.log() of the post route in NodeJS I'm getting undefined as well. 在NodeJS中发布路由的console.log()中,我也变得不确定。 Seems like the body-parser is not working or I'm missing something else. 似乎人体分析器无法正常工作,或者我缺少其他功能。
The angular $http.post
function will send a JSON body rather than a urlencoded body. 有角的$http.post
函数将发送JSON正文,而不是urlencoded正文。
Add this middleware to parse JSON objects: 添加此中间件以解析JSON对象:
app.use(bodyParser.json());
I had a same problem and this is how I solved it. 我遇到了同样的问题,这就是我解决的方法。
Change this part 改变这部分
response.status(201).json(request.body.name);
to 至
response.write(request.body.name);
response.end();
I hope it will solve your problem. 希望它能解决您的问题。 but I'm not sure why it is working. 但我不确定为什么会起作用。 I hope someone explain it. 我希望有人能解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.