【问题标题】:Can't get POST data in NodeJS from Angular app无法从 Angular 应用程序获取 NodeJS 中的 POST 数据
【发布时间】:2015-08-04 06:56:16
【问题描述】:

我无法从 Angular 应用创建的 POST 方法中获取参数。我尝试在这里寻找答案,甚至复制/粘贴一些示例,但似乎没有任何效果。

节点代码:

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');
});

Angular 代码:

$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);
    })
}

我可以在开发人员工具的网络面板上看到数据已发送,我什至按预期获得了 201 的 http 代码,但我没有收到回复。在 NodeJS 的 post 路由的 console.log() 中,我也变得未定义。似乎正文解析器无法正常工作,或者我缺少其他内容。

【问题讨论】:

    标签: javascript angularjs node.js


    【解决方案1】:

    角度 $http.post 函数将发送 JSON 正文而不是 urlencoded 正文。

    添加此中间件以解析 JSON 对象:

    app.use(bodyParser.json());
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,我就是这样解决的。

      改变这部分

      response.status(201).json(request.body.name);

      response.write(request.body.name);

      response.end();

      希望它能解决您的问题。但我不确定它为什么起作用。希望有人解释一下。

      【讨论】:

        猜你喜欢
        • 2018-04-27
        • 2017-06-23
        • 2017-06-16
        • 1970-01-01
        • 2015-10-22
        • 1970-01-01
        • 2021-08-17
        • 2016-07-09
        • 2017-07-18
        相关资源
        最近更新 更多