节点JS类型错误:无法读取属性

时间:2019-12-28 22:56:47

标签: javascript node.js express

我是一个nodejs初学者开发人员,一开始我决定开发一个博客项目进行练习。我在客户端上使用Nodejs Express和本机js。添加帖子时,nodejs在路由中引发错误:
(节点:25967)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ title” 在router.post(/routes/post.js:15:25)
这是我的代码:


routes / post.js

throw/1

app.js

const express = require('express');
const router = express.Router();
const Post = require('../models/Post');

// http://localhost:5000/api/post (GET)
router.get('/', async (req, res) => {
    const posts = await Post.find({})
    res.status(200).json(posts)
})

// http://localhost:5000/api/post (POST)
router.post('/', async (req, res) => {

    const postData = {
        title: req.body.title,
        text: req.body.text
    }

    const post = new Post(postData)

    await post.save()
    res.status(201).json(post)
})

// http://localhost:5000/api/post/id (DELETE)
router.delete('/:postId', async (req, res) => {
  await  Post.remove({_id: req.params.PostId})
  res.status(200).json({
      message: 'Deleted'
  })
})




module.exports = router

(模型) Post.js

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const postRouter = require('./routes/post');
const keys = require("./keys");

const port = process.env.PORT || 5000;
const clientPath = path.join(__dirname, 'client');

const app = express();
app.use(express.static(clientPath))
app.use('/api/post', postRouter)
app.use(bodyParser.json())


mongoose.connect(keys.mongoURI, { useNewUrlParser: true, 
    useUnifiedTopology: true, useCreateIndex: true })
    .then(() => console.log('MongoDB connected'))
    .catch( err => console.error(err));



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

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

这是一个订购问题,请在以下几行之间切换:

app.use('/api/post', postRouter)
app.use(bodyParser.json())

Express middlewere按顺序运行 ,在您的情况下,这意味着您的发布路线将在 之前被称为bodyParser中间件能够解析JSON主体。