当我拥有键和值时,为什么会出现错误?

时间:2018-08-21 03:55:03

标签: javascript node.js express

即使我已输入带有firstName键和填写值的请求,仍收到错误“在请求字段中缺少firstName”。有人有什么想法吗?我真的很需要帮助,因为我是新手。作者是猫鼬收藏,我正在尝试通过“ if”语句并返回作者列表。

app.post('/authors', function (req, res) {
const requiredFields = ['firstName', 'lastName', 'userName'];
requiredFields.forEach(field => {
    if (!(field in req.body)) {
        const message = `Missing \`${field}\` in request body`;
        console.error(message);
        return res.status(400).send(message);
    }
});

Author
    .findOne({
        userName: req.body.userName
    })
    .then(author => {
        if (author) {
            const message = `Username already taken`;
            console.error(message);
            return res.status(400).send(message);
        } else {
            Author
                .create({
                    firstName: req.body.firstName,
                    lastName: req.body.lastName,
                    userName: req.body.userName
                })
                .then(author => res.status(201).json({
                    _id: author.id,
                    name: `${author.firstName} ${author.lastName}`,
                    userName: author.userName
                }))
                .catch(err => {
                    console.error(err);
                    res.status(500).json({
                        error: 'Something went wrong'
                    });
                });
        }
    })
    .catch(err => {
        console.error(err);
        res.status(500).json({
            error: 'Something went really really wrong'
        });
    });
});

2 个答案:

答案 0 :(得分:1)

解决方案可以为以下

之一
  1. 检查是否正确使用了正文解析器(取决于您的输入),
const express = require('express');
const app = express();
const bodyParser = require('body-parser'); 
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/authors', function (req, res) {
    const requiredFields = ['firstName', 'lastName', 'userName'];
    console.log(req.body);
    requiredFields.forEach(field => {

        if (!(field in req.body)) {
            const message = `Missing \`${field}\` in request body`;
            console.error(message);
            return res.status(400).send(message);
        }
    });
    //Your Other code



});
  1. 确保在请求中使用以下标头,
  

Content-Type:应用程序/ json

所有条件都满足了,我可以使上面的代码正常工作。

答案 1 :(得分:0)

如果您使用Express 4.16.0或更高版本,则可以使用以下命令: app.use(express.json());