Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

express - Key passed but validation fails in postman

I have this patch request where I update certain information depending on object of a document. When I send request using Postman(form-data) I get validation error saying "_id" is required.

Here's how it looks in Postman,

enter image description here

The route looks similar to this,

router.patch("/update", async (req, res) => {
    try{
        await updateValidation(req.body);
        // whatever stuff processed with the data
    } catch (err) {
       res.status(400).send({ message: err.details[0].message });
    }
}

The validation function looks like this,

const updateValidation = (data) => {
    const schema = Joi.object({
        _id: Joi.string().required(),
        // other whatever validation possible
    });

    return schema.validateAsync(data);
};

Am I missing something here? I think I do, please point it out.

question from:https://stackoverflow.com/questions/65650767/key-passed-but-validation-fails-in-postman

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Besides using var bodyParser = require('body-parser'); in server side, it will still return empty req.body that will lead to errors because you have validation in place. The reason it is returning empty req.body when you sending PATCH request using form-data in Postman is because body-parser can't handle multipart/form-data. You need a package that can handle multipart/form-data like multer. at the first to install the body-parser and multer, go to your terminal and use ?

npm install --save body-parser multer

so add this code to in server.js

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var app = express();

at the next time use this middelware:

// for parsing application/json
app.use(bodyParser.json()); 

// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true })); 
//form-urlencoded

// for parsing multipart/form-data
app.use(upload.array()); 
app.use(express.static('public'));

After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...