Node.js 使用nodejs将数据保存到mongodb

Node.js 使用nodejs将数据保存到mongodb,node.js,mongodb,Node.js,Mongodb,我是自学型nodeJS,现在我尝试在MongoDB中插入数据,这是我的目标 在此处插入值,单击提交按钮后,应将数据成功保存到mongodb,并返回一条成功消息 但这就是错误所在 TypeError: Cannot read property 'location' of undefined 下面是代码片段 const express = require('express'); const dotenv = require("dotenv").config(); const

我是自学型nodeJS,现在我尝试在MongoDB中插入数据,这是我的目标

在此处插入值,单击提交按钮后,应将数据成功保存到mongodb,并返回一条成功消息

但这就是错误所在

TypeError: Cannot read property 'location' of undefined
下面是代码片段

const express = require('express');
const dotenv = require("dotenv").config();
const address = process.argv[2];
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const app = express();

//INSERT TO MONGO DB
//connect to mongo db
mongoose.connect('mongodb://localhost/weathertest2');
mongoose.Promise = global.Promise;


//create weather schema
const WeatherSchema = new Schema({
    location:{
        type: String
    },
    temperature:{
        type: String
    },
    observationTime:{
        type: String
    }

});

const Weather = mongoose.model('weather', WeatherSchema);

// post request
app.post('/new', function(req, res){
    new Weather({
        location    : req.body.location,
        temperature: req.body.temperature,
        observationTime   : req.body.observationTime                
    }).save(function(err, doc){
        if(err) res.json(err);
        else    res.send('Successfully inserted!');
    });
});
 

// listen for request
app.listen(process.env.port || 9000, function(){
    console.log('now listening for  testing request');
});
app.use(express.static('public'));

尝试将
正文解析器
中间件与express一起使用:

constbodyparser=require(“bodyParser”);
/* 
*将文本解析为URL编码的数据(这是浏览器倾向于发送的方式)
*常规表单中的表单数据(设置为POST)和
*在req.body上公开结果对象(包含键和值)
*/
use(bodyParser.urlencoded({extended:true}));

这样,表单中的数据应该包含在请求
正文中(
req.body.location

尝试使用
正文解析器
中间件和express:

constbodyparser=require(“bodyParser”);
/* 
*将文本解析为URL编码的数据(这是浏览器倾向于发送的方式)
*常规表单中的表单数据(设置为POST)和
*在req.body上公开结果对象(包含键和值)
*/
use(bodyParser.urlencoded({extended:true}));

通过这种方式,表单中的数据应该包含在请求
正文
req.body.location

请求正文似乎未定义。这可能是因为express没有正确解析请求体。解决方案可能是使用主体解析器

npm install --save body-parser
然后将主体解析器导入文件:

const bodyParser = require('body-parser')
然后将此行放在“/new”处理程序之前:


请求的主体似乎没有定义。这可能是因为express没有正确解析请求体。解决方案可能是使用主体解析器

npm install --save body-parser
然后将主体解析器导入文件:

const bodyParser = require('body-parser')
然后将此行放在“/new”处理程序之前:


很高兴我能帮助@rickyProgrammer!我想问,我如何返回输入值的温度为例?请创建另一个问题!谢谢很高兴我能帮助@rickyProgrammer!我想问,我如何返回输入值的温度为例?请创建另一个问题!谢谢在这里