Validator error when POSTing. Creating a RESTful A

2019-08-25 06:22发布

问题:

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 }
});

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
            });
        }
    });
});

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

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'.

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

回答1:

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.

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