javascript - angularjs http.POST 不包含数据

标签 javascript angularjs node.js

我正在开始学习 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 函数得到的输出是 Trying to create – {title: "amazingTitle",author: "amazingAuthor"},这是应该的,但 API 处理程序的输出是 New book: {},这当然不是我想要的。我意识到这可能还不够详细,但我可能在哪里出错了?

最佳答案

事实证明,这是 body-parser 设置的错误,我只将应用程序设置为使用 urlencoded,而不是 json。

关于javascript - angularjs http.POST 不包含数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38029860/

相关文章:

javascript - 我们可以在 AngularJS 的 ng-options 中使用 split 吗?

javascript - 在 `bundle.js` 创建 `cachebust.resources()` 之后如何从 html 引用 `bundle.a3503174.js` ?

node.js - Amazon Lambda 上来自 ffmpeg 的 SIGSEGV

node.js - NodeJS Async/Await 不等待(返回 Promise pending)

javascript - li 标签的重复 onmouseover/onmouseout 调用

html - 当我使用 ngRouter 时,导航栏不会折叠

c# - ASP :hyperlink navigation

angularjs - 检测是否已为 angularjs 指令给出嵌入内容

javascript - Angular 变量未绑定(bind)到 View

php - 如何显示谷歌地图?