Post 节点中的方法呈现 500 错误

Post method in node renders 500 error

我在节点中有几个 post 方法。其中一个有效,现在我正在研究另一个。我已经尝试过切换 res.body 中键值对的顺序、重新启动后端服务器以及其他一些操作,但现在我没有主意了。我正在使用 postman,所以这可能是一个问题,但也许你们会看到一个我没有看到的明显错误。

这是模型:

var UserGameSchema = new mongoose.Schema({
user: { type: String, required: true },
game: { type: String, required: true },
own: { type: Boolean, required: true }
});

var UserGame = mongoose.model('UserGame', UserGameSchema);

module.exports.UserGame = UserGame;

这是我的方法:

app.post('/mygames', function(req, res) {
UserGame.create({
    user: req.body.user,
    game: req.body.game,
    own: req.body.own
}, function(err, item) {
    if (err) {
        return res.status(500).json({
            message: 'Internal Server Error'
        });
    }
    res.status(201).json(item);


   });
});

这是我使用 Postman

发送的 res.body
{
"user": "Colin",
"own": true,
"game": "Grand Theft Auto 5 (PS4)"
}

是的,我很确定我使用的是正确的URL:http://localhost:8080/mygames

仍然收到此 500 错误。具体来说 postman 在控制台中返回:

TypeError: Cannot read property 'user' of undefined

我不确定为什么用户会是未定义的。

感谢任何反馈。

如果要查找太多信息,这里是 github 存储库: https://github.com/auldsy-ababua/gameswap

您只为 one specific route 使用 body-parser:

app.post('/users', jsonParser, function(req, res) { ... });

所以它没有被用于 POST /mygames 路线。也可以在那里添加,或者全局添加:

app.use(jsonParser);

...your routes...