javascript - Node JS 类型错误 : Cannot read property

标签 javascript node.js express

我是一名初学者 Nodejs 开发人员,首先我决定开发一个博客项目进行练习。我在客户端使用 Nodejs Express 和原生 js。添加帖子时,nodejs 在路由中抛出错误:
( Node :25967)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“标题” 在 router.post (/routes/post.js:15:25)
这是我的代码:


routes/post.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

app.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}`);
});

(模型)Post.js

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

const postSchema = new Schema ({
    title: {
        type: String,
        required: true,
    },
    text: {
        type: String,
        required: true
    },
    date : {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('posts', postSchema)

可能是什么问题?

最佳答案

这是一个排序问题,请交换这些行:

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

Express middlewere按顺序运行,在您的情况下,这意味着您的发布路由将在 bodyParser 中间件能够解析 JSON 正文之前被调用。

关于javascript - Node JS 类型错误 : Cannot read property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515564/

相关文章:

javascript - CasperJS 后退导航不起作用

javascript - html5音频播放器flash后备

node.js - 带有 KnexJs 的 AWS Lambda(node12.x) 仅在第一次运行时调用,随后会失败

node.js - 使用 Node.js 获取输入 HTML 的 DOM 对象

javascript - 使用 app.set() 和 app.get() 是否有目的?

node.js - 在客户端 JavaScript (nunjucks) 中访问 Express.js 局部变量

node.js - Mongoose 架构错误 : "Cast to string failed for value" when pushing object to empty array

javascript - RadTabStrip - 隐藏选项卡客户端

google-maps - Google Place Autocomplete API 未以正确的语言返回结果

node.js - 如何从 Promise Sequelize 返回值