can anyone help me for the issue of Javascript post call is sending null value to mongoDB?

Issue

I am a beginner in JS, NodeJS, and MongoDB. I created a quiz website to practice my coding skills and I am facing the issue while sending the username (string) and total marks (int) to mongo DB via Post method. it is sending null values only. When I hardcode the values in the app.js file, it inserts the data correctly to DB correctly, but via JS, there are only null values. adding code below:

index.js (username is string and marks is number)

var obj = {
        name:username,
        total:marks
    }
console.log(JSON.stringify(obj))
fetch('/index', {method:'POST', body:JSON.stringify(obj)});

app.js

const express = require('express')
const app = express()
app.use(express.urlencoded());
app.use(express.json());
const path = require('path')
const port = process.env.port || 80

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/dataDB', {useNewUrlParser: true})
// const dataSchema = new mongoose.Schema({total:Number});
const dataSchema = new mongoose.Schema({
    name:String,
    total:Number
});
const data = mongoose.model('data',dataSchema);

app.use('/static', express.static('static'))


app.set('view engine','pug')
app.set('views', path.join(__dirname,'views'))

app.get('/',(req,res) => {
    const params = {}
    res.status(200).render('index.pug',params);
});
app.post('/index',(request,res) => {
        console.log(JSON.stringify(request.body)); //---giving null
        console.log(request.body); //---giving null
        console.log(JSON.stringify(request.body.name)); //---giving null
        console.log(request.body.name); //---giving null
        var userData = new data(request.body)
        userData.save().then(()=>{
            console.log("data saved into DB")
        }).catch(()=>{
            console.log("data not saved")
        });
});

app.listen(port, () => {
    console.log(`application has been started at ${port}`)
})

Solution

Try setting the header, while sending the request:

fetch('/index',
 {method:'POST', headers: {
    'Content-Type': 'application/json',
  },
body:JSON.stringify(obj)});

Answered By – Charchit Kapoor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published