[Fixed] req.body is returning object but object comes out to be undefined in nodejs

Issue

The code Combines expressjs NodeJs and Mongodb

When I console log req.body it comes out to be
[object Object]
but when I console log req.body.name it comes out to be undefined.I am sending data through POST method like this through POSTMAN
{
"name":"vaibhav",
"tech":"NodeJS",
}

my program is this
app.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const url = 'mongodb://localhost:27017/Alien';

mongoose.connect(url, {useNewUrlParser:true});
const conn = mongoose.connection;    //handle of db
conn.on("open", function(){
    console.log('connected....');
})
app.use(express.json())


const alienRouter = require("./routers/aliens");
app.use('/alien', alienRouter);




app.listen(9000, (err)=>{
    if(err){
        console.log("error in starting server")
    }
    else{
        console.log("Listening on port 9000")
    }
})

router/alien.js

const express = require("express");
const router = express.Router();
const Alien = require("../models/alien")

router.get("/", async(req, res)=>{
    try{
        const aliens = await Alien.find()
        res.json(aliens)
    }
    catch(err){
        res.send("Error" + err)
    }
})

router.get("/:id", async(req, res)=>{
    try{
        const aliens = await Alien.findById(req.params.id)
        res.json(aliens)
    }
    catch(err){
        res.send("Error" + err)
    }
})

//POST METHOD
router.post("/", async(req, res)=>{
    console.log("body "+req.body);
    const alien = new Alien({
        name: req.body.name,
        tech: req.body.tech,
        sub: req.body.sub
    })

    try{
        const al = await alien.save();
        res.json(al);
    }catch(err){
        res.send("Error: "+err)
    }
    
})

module.exports = router;

model/alien.js

const mongoose = require("mongoose");

const alienSchema  = new mongoose.Schema({
    name:{
        type:String,
        require:true,
    },
    tech:{
        type:String,
        reqired:true
    },
    sub:{
        type:Boolean,
        required:true,
        default:false
    }

})

module.exports =  mongoose.model('Alien', alienSchema);

can anyone help me with this??

Solution

Your POSTMAN request is sending text/plain instead of application/json. That is why your express.json() middleware is not parsing the request and putting data into req.body.

You need to fix your POSTMAN request so that it formats the data as JSON and sends the right content-type.

Leave a Reply

(*) Required, Your email will not be published