【问题标题】:how to fix ".... validation failed" using postman with express/bodyParser如何使用带有 express/bodyParser 的邮递员修复“....验证失败”
【发布时间】:2020-01-30 18:11:17
【问题描述】:

我正在使用 express/bodyparser/MongoDB/postman 制作 API,但是每当我发送 POST 请求时,Schema 都会返回错误,我该如何解决这个问题?

我在 Postman 中尝试了不同的选项,例如检查我是否有正确的选项并确保其设置为 JSON。

我的要求如何:

const express = require("express");
const app = express();
const todoRoutes = require("./routes/todos");
const bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

我的架构是什么样子的:

var todoSchema = new mongoose.Schema({
  name: {
    type: String,
    required: "Use a string"
  },
  completed: {
    type: Boolean,
    default: false
  },
created_date: {
  type: Date,
  default: Date.now
}
});

我的 POST 请求的外观:

router.post("/",function(req,res){
  console.log(req.body);
db.Todo.create(req.body)
.then(function(newTodo){
  res.json(newTodo);
})
.catch(function(err){
  res.send(err);
});
});

邮递员返回的错误:

{
    "errors": {
        "name": {
            "message": "Use a string",
            "name": "ValidatorError",
            "properties": {
                "message": "Use a string",
                "type": "required",
                "path": "name"
            },
            "kind": "required",
            "path": "name"
        }
    },
    "_message": "Todo validation failed",
    "message": "Todo validation failed: name: Use a string",
    "name": "ValidationError"
}

当我给出名称键和 GoT 值时,req.body 的 console.log :

'{\n "name" : "watch GoT"\n}': " }

我看到的主要奇怪的事情是,出于某种原因,我首先从 req.body 得到了一个奇怪的日志(不寻常的'和\n)

【问题讨论】:

  • 您在 Postman 中的请求是什么样的?你要寄什么?
  • @DannyDainton 我正在为我的数据库发送一个测试条目,其键为“name”,值为“Got”。但它不被我所做的模式所接受,回馈“不是字符串”
  • 你能用一张图片更新问题吗?
  • @DannyDainton 更新了它,请注意,我也使用 选项卡以相同的结果做了完全相同的事情

标签: mongodb express postman body-parser


【解决方案1】:

要发布 URL 参数的值,请使用 req.params

   router.post("/",function(req,res){

   db.Todo.create({ name = req.params.name })
   .then(function(newTodo){
    res.json(newTodo);
    })
    .catch(function(err){
    res.send(err);
    });
     });

【讨论】:

    【解决方案2】:

    你需要在 Postman 的 body 选项卡中选择 xxx-w-form-urlencoded

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2021-04-15
      • 2018-03-12
      • 2016-11-26
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      相关资源
      最近更新 更多