POST 时验证器错误.创建 RESTful API [英] Validator error when POSTing. Creating a RESTful API

查看:30
本文介绍了POST 时验证器错误.创建 RESTful API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为任务管理实现一个 API,并且有两个端点用户和任务.用户"的架构设计如下所示:

I am implementing an API for a task management and has two endpoints users and tasks. The schema design for the 'users' looks like:

var userSchema = new mongoose.Schema({
    name: { 
        type:String,
        required: true
    },

    email: {
        type: String,
        required: true,
        unique: true
    },

    pendingTasks: [String],

    dateCreated: { 
        type: Date, 
        default: Date.now }
});

我的 POST 看起来像

and my POST looks like

router.post('/', function(req, res){
    var userPost = {
        name: req.body.name,
        email: req.body.email
    }
    user.create(userPost, function(err, users){
        if(err) {
            res.status(500).send({
                message:err,
                data: []
            });
        } else {
            res.status(201).send({
                message: 'OK',
                data: users
            });
        }
    });
});

当我尝试使用虚拟数据在邮递员上测试我的 POST 时

When I try to test my POST on postman with a dummy data by doing

我收到一个ValidatorError",它给我一条消息,上面写着用户验证失败:电子邮件:路径‘电子邮件’是必需的,名称:路径:‘名称’是必需的.

I am getting a "ValidatorError" and it gives me a message that says "User validation failed: email: Path 'email' is required, name: Path: 'name' is required.

这看起来很奇怪,因为我刚刚传入了虚拟数据姓名"和电子邮件".

This seems weird because I just passed in dummy data 'name' and 'email'.

我是创建 RESTful API 的新手,所以我可能犯了一个愚蠢的错误,但我真的不明白.

I am new to creating RESTful API so I might be making a stupid mistake, but I really don't get it.

推荐答案

我还在本地 PC 上部署了一个应用程序并进行调试,如果您选择 raw 作为您的身体类型,req.body 对象中将不存在 email 属性.

I have also deployed an app in my local PC and debug, if you select raw as your body type, the email property will NOT be exist in the req.body object.

要在 Postman 中解决此问题,您必须选择 x-www-form-urlencoded 并将您的数据作为键值对输入:

To solve this problem in Postman, you have to select x-www-form-urlencoded and input your data as key-value pairs:

这篇关于POST 时验证器错误.创建 RESTful API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆