提问人:Saurabh Kulkarni 提问时间:8/23/2022 更新时间:8/24/2022 访问量:50
谁能帮我解决Javascript后调用向mongoDB发送null值的问题?
can anyone help me for the issue of Javascript post call is sending null value to mongoDB?
问:
我是 JS、NodeJS 和 MongoDB 的初学者。我创建了一个测验网站来练习我的编码技能,在通过 Post 方法将用户名(字符串)和总分 (int) 发送到 mongo DB 时遇到了这个问题。它仅发送 null 值。当我对app.js文件中的值进行硬编码时,它会正确地将数据正确地插入数据库,但通过 JS,只有空值。在下面添加代码:
index.js(用户名是字符串,标记是数字)
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}`)
})
答:
2赞
Charchit Kapoor
8/24/2022
#1
尝试在发送请求时设置标头:
fetch('/index',
{method:'POST', headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify(obj)});
评论