邮递员发布请求无法读取未定义的属性

时间:2018-12-02 07:59:57

标签: node.js mongodb postman

我的快递服务器中有一个路由设置,该路由发送一个发布请求并在mongoDB数据库中添加一条新消息。

当我在主体字段中静态添加名称时;即new userMessage = new Message({ name: 'Joseph', email: 'joseph@gmail.com', message: 'Hello Joseph'}),它发布成功。

但是当它是动态的时;即new userMessage = new Message({ name: req.body.name, email: req.body.email, message: req.body.message})会引发错误。

我已经尝试过几次调试问题,但均未成功。

错误

TypeError: Cannot read property 'name' of undefined
    at router.post (C:\Users\Joseph\Documents\Hackathons\hack.api\app\routes\message.js:13:24)
    at Layer.handle [as handle_request] (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\express\lib\router\index.js:275:10)
    at cors (C:\Users\Joseph\Documents\Hackathons\hack.api\app\node_modules\cors\lib\index.js:188:7)

Message.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MessageSchema = new Schema({
    name: { type: String, required: true },
    email: { type: String, required: true },
    message: { type: String, required: true }
});

module.exports = Message = mongoose.model('message', MessageSchema);

Server.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');

const message =  require('../routes/message');

const app = express();

//Enable cors
app.use(cors( {origin: '*' }));

//Connect to mongoose
mongoose.connect('mongodb://localhost/messages', { useNewUrlParser: true })
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.log(err));

//Use routes
app.use('/message', message);

//Body Parser middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

//Test route
app.get('/', (req, res) => {
    res.send('Hello world');
})

//Set server port
const port = process.env.PORT || 5000;

app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});  

message.js

const express = require('express');
const router = express.Router();

//Load message model
const Message = require('../models/Message');

router.get('/test', (req, res) =>
    res.json({ msg: 'Message post route works' })
);

router.post('/post', (req, res) => {
    const userMessage = new Message({
        name: req.body.name,
        email: req.body.email,
        message: req.body.message
    });

    userMessage.save()
        .then(message => res.json(message))
        .catch(err => console.log(err))
});

module.exports = router;

3 个答案:

答案 0 :(得分:0)

在创建新的Mongo对象之前,最好先获取数据并进行验证:

const { body: {name, email, message } } = req;
//validate email for example or you just logs it to know data reviced or not? 
const userMessage = new Message({
        name: name,
        email: email,
        message: message
    });

答案 1 :(得分:0)

如果要从客户端发送嵌套对象,例如person[name] = 'cw',则必须编写app.use(bodyParser.urlencoded({extended: true}));,否则,请确保html表单中的输入具有{{1} }属性。

答案 2 :(得分:0)

我通过将

 var scheduledNotificationDateTime =
        new DateTime.now().add(new Duration(seconds: 5));
  var androidPlatformChannelSpecifics =
     new AndroidNotificationDetails('your other channel id',
    'your other channel name', 'your other channel description');
  var iOSPlatformChannelSpecifics =
   new IOSNotificationDetails();
   NotificationDetails platformChannelSpecifics = new 
  NotificationDetails(
   androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
  await flutterLocalNotificationsPlugin.schedule(
 0,
 'scheduled title',
 'scheduled body',
 scheduledNotificationDateTime,
 platformChannelSpecifics);

更改为

 aclass = asset class (optional):

    currency (default)

 asset = asset being withdrawn

 key = withdrawal key name, as set up on your account

 amount = amount to withdraw, including fees

解决了这个问题,我想顺序很重要。在服务器配置中,顺序确实很重要。