简体   繁体   中英

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

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}`)
})

Try setting the header, while sending the request:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM