Adnan Ahmed
Adnan Ahmed

Reputation: 516

Request body is empty in Post

The following is a test file written with reference to my previous question:model.save() returns an invalid output .

// Imports
var express=require("express")
, mongoose=require("mongoose")
, bodyParser= require('body-parser')
, bodyParser = require("body-parser");
const { Int32 } = require("bson");


// Constants
const app = express()
const PORT=4002

// Create a model
const dataModel=mongoose.model('dataCollection',mongoose.Schema(data))




// Our Schema
var data={
    value: Number
}

// Making connection with database
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/testdb', {
    useNewUrlParser:true,
    useUnifiedTopology:true
})


// Create the controller to save data
function postData(req,res){
    console.log(req.body)
    let newData = new dataModel(req.body)
    newData.save((err,resp)=>{
        if(err) console.log(err)
        else res.json(resp)
    })
}

// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));

// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);

// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

// start listening on server
app.listen(PORT,()=>console.log(`Your application is running on Port: ${PORT}`));



The above code prints undefined for console.log(req.body) in controller function postData for the POST request shown here: enter image description here

Upvotes: 1

Views: 106

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14924

You can imagine the request is coming from the top and goes to the bottom.

It does not make sense to parse the body after you visited the route. You need to parse the body first and THEN visit the route.

// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));

// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);

However bodyparsers isnt used anymore. You can use instead app.use(express.json())

Upvotes: 2

Related Questions