【问题标题】:postman "Error: ValidationError: username: Path `username` is required."邮递员“错误:ValidationError:用户名:路径‘用户名’是必需的。”
【发布时间】:2020-02-28 11:10:27
【问题描述】:

我正在尝试使用邮递员测试我的路线。 以下是我的 user.model.js 文件

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3
  },
}, {
  timestamps: true,
});

const User = mongoose.model('User', userSchema);

module.exports = User;

我的用户路由器文件在下面

const router = require('express').Router();
let User = require('../models/user.model');

router.route('/').get((req, res) => {
    User.find()
        .then(users => res.json(users))
        .catch(error => res.status(400).json('Error: ' + error));
});

router.route('/add').post((req, res) => {
    const username = req.body.username;

    const newUser = new User({ username });

    newUser.save()
        .then(() => res.json('User added!'))
        .catch(error => res.status(400).json('Error: ' + error));
});

module.exports = router;

每次我尝试为用户测试发布路线时,我都会收到“错误:ValidationError:用户名:路径username 是必需的。”错误 下面是我邮递员的截图

谁能帮我弄清楚我错在哪里。

【问题讨论】:

  • 你的路由器里有 req.body.username 吗?
  • 通过添加如下标题,它可以工作。点击 Postman 中的 Headers 按钮并输入值 Content-Type application/json

标签: node.js mongodb mongoose postman


【解决方案1】:

更改您的 /add 路由器:

const newUser = new User({ username : username }); // 改变

您必须以这种方式传递您的用户名。希望这会对您有所帮助。如果您有任何错误,请告诉我。

【讨论】:

  • @Prakesh Karena 如果我将从用户名字段中删除所需的属性,那么我可以将我的信息发布到我的路线
  • 你检查过你的数据库存储用户名吗?
【解决方案2】:

您传递的数据应该是 JSON 格式,而不是多部分格式。如下更改您的 Postman 请求并检查。

【讨论】:

    【解决方案3】:

    我遇到了同样的问题。我可以通过在我的程序中添加下一部分来解决这个问题:

    const bodyParser = require("body-parser");
    
    app.use(bodyParser.urlencoded({ extended: false })); 
    app.use(bodyParser.json());
    

    我的 bodyparser 版本是“^1.15.2”

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多