Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 920
Tahmid Hasan Avatar asked Dec 23 '22 10:12

Tahmid Hasan


1 Answers

you missing

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

then try in x-www-form-urlencoded

like image 182
M ilham Avatar answered Jan 14 '23 01:01

M ilham