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

11,708

Solution 1

you missing

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

then try in x-www-form-urlencoded

Solution 2

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

Solution 3

Use multer middleware:

const upload = require('multer')();

route.post('/', upload.any(), (req, res) => {
    // your code...
});

Solution 4

  • 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(i.e 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

Solution 5

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.

Share:
11,708

Related videos on Youtube

Tahmid Hasan
Author by

Tahmid Hasan

Hard-working listing full-stack developer with a flair for creating elegant solutions for web in the least amount of time. As a freelance programmer, provided real-time web based solution and developed web service in MEAN-stack strategy to improve efficiency of web apps. Looking to use my programming skills to help boost IT Companies' who needs web solutions for their own or client.

Updated on September 16, 2022

Comments

  • Tahmid Hasan
    Tahmid Hasan over 1 year

    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);
    
  • Tahmid Hasan
    Tahmid Hasan about 6 years
    Sorry! I've a file duplication on product.js. I simply remove that file and now it works for me. Thanks for your reply. :)
  • Pooja Khatri
    Pooja Khatri about 6 years
    I don't have any duplication of the file then also I am getting the error. It happens when I try with form-data, If I am trying with row data its giving right output. But when I give with form data its shows error.