【问题标题】:angular.js http.POST contains no dataangularjs http.POST 不包含数据
【发布时间】:2016-06-26 01:46:28
【问题描述】:

我刚开始学习 MEAN 堆栈,所以很抱歉这是一个愚蠢的问题。我正在为我自己的项目改编一些教程,并且我已经为书籍数据库制作了一个简单的 REST api。

// add book and return updated list
app.post('/api/books', function(req, res) {
    console.log("New book: ", JSON.stringify(req.body, null, 4));
    Book.create({
        title: req.body.title,
        author: req.body.author,
        pageCount: 100,
    }, function(err, book) {
        if (err)
            res.send(err);

        // get and return updated list
        Book.find(function(err, books) {
            if (err)
                res.send(err);
            res.json(books);
        });
    });
});

我正在尝试使用 angular 来与此交互,如下所示:

$scope.createBook = function() {
    console.log('Trying to create ', $scope.formData);
    $http({ method: 'POST', url: '/api/books', data: $scope.formData}).then(function (response) {
        $scope.formData = {};   // reset form
        console.log('CREATE Success: ', response);
    }, function (error) {
        console.log('CREATE Error: ', error);
    });
};

我从createBook-function 得到的输出是Trying to create – {title: "amazingTitle", author: "amazingAuthor"},应该是这样,但是API 处理程序的输出是New book: {},这当然不是我想要的。我意识到这可能不够详细,但我可能会在哪里出错?

【问题讨论】:

  • 这可能会帮助您执行console.log("New book: " + JSON.stringify(req.body, null, 4)); 以查看对象包含的确切内容
  • 另外,这是一个小细节,.success().error() 已弃用。最好将返回的 Promise 与 .then(successCB, failureCB) 一起使用
  • @pulseOne 谢谢,我试过了,我得到了新书:{}
  • 检查浏览器调试工具是否将它们发布到服务器并确保您在服务器端使用正文解析器模块
  • 在您的节点服务器中,您使用的是正文解析器吗?

标签: javascript angularjs node.js


【解决方案1】:

原来是 body-parser 设置出错,我只是将应用设置为使用 urlencoded,而不是 json。

【讨论】:

    【解决方案2】:

    JSON.stringify() 你的数据。

    参考AngularJS - $http.post send data as json

    我的 POST 调用通常采用以下形式:

    $http({method: 'POST', url: url, headers: headers, data: JSON.stringify(request)}).then(function(response) {
            var data = response.data;
            // do something
        }, function(error) {
            // do something
        });
    

    【讨论】:

    • 无需字符串化...默认在$httpapi内部完成
    • $http.post('/api/books', $scope.formData) 的 OP 签名没有问题。我个人经常使用它
    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多