如何使用Express / bodyParser的邮递员修复“ ....验证失败”

时间:2019-10-01 12:40:14

标签: mongodb express postman body-parser

enter image description here我正在使用express / bodyparser / MongoDB / postman制作API,但是每当我发送POST请求时,架构都会返回错误,该如何解决此问题?

我在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)

2 个答案:

答案 0 :(得分:0)

要发布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);
    });
     });

答案 1 :(得分:0)

您需要转到Postman中的“正文”标签,然后选择xxx-w-form-urlencoded

this should clear it up