简体   繁体   中英

Postman raw data works but form-data not works on POST request in node

I'm facing some problem when using postman. When I'll try to send raw data in JSON(application/json) format, it get success.

Postman sending post request and succeded

But when I'll try to send form data it returns some error.

{
    "error": {
        "errors": {
            "name": {
                "message": "Path `name` is required.",
                "name": "ValidatorError",
                "properties": {
                    "message": "Path `{PATH}` is required.",
                    "type": "required",
                    "path": "name"
                },
                "kind": "required",
                "path": "name",
                "$isValidatorError": true
            },
            "price": {
                "message": "Path `price` is required.",
                "name": "ValidatorError",
                "properties": {
                    "message": "Path `{PATH}` is required.",
                    "type": "required",
                    "path": "price"
                },
                "kind": "required",
                "path": "price",
                "$isValidatorError": true
            }
        },
        "_message": "Product validation failed",
        "message": "Product validation failed: name: Path `name` is required., price: Path `price` is required.",
        "name": "ValidationError"
    }
}

Postman errors

And here is my project code snippets

product.js

import express from 'express';
import mongoose from 'mongoose';
import Product from '../models/product.model';

router.post('/', (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price
    });
    product.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

product.model.js

import mongoose from 'mongoose';

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {type: String, required: true},
    price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', productSchema);

you missing

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

then try in x-www-form-urlencoded

You need to use body-parser.

npm install body-parser --save

Then just add in your code

var bodyParser = require('body-parser')

app.use(bodyParser.json())

Details can be found https://www.npmjs.com/package/body-parser

Besides using body-parser, 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 sending POST request using form-data tru Postman is because body-parser can't handle multipart/form-data. You need a package that can handle multipart/form-data like multer. See https://www.npmjs.com/package/multer . Try using that package.

// use multer as a middileware and use upload.any() method problem solved.

    const multer = require('multer);

    const upload = multer();


    route.post('/' , upload.any(), (req,res) => {
              
                 // your code...
    });
  • Use multer for get form data

  • inside upload function you can get req.body from form data

https://www.npmjs.com/package/multer

  • Any data sent using postman's formdata is considered as multipart/formdata . You have to use multer or other similar library in order to parse formdata.
  • For x-www-form-urlencoded and raw data from postman does not require multer for parsing. You can parse these data either using body-parser or express built-in middlewares express.json() and express.urlencoded({ extended: false, })
  • Since multer returns a middleware, you can only access req.body inside multer(ie fileFilter) or in the middleware that comes after multer BUT NOT BEFORE if you have not used multer as global middleware(which is bad idea).

for code snippets: https://stackoverflow.com/a/68588435/10146901

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM