【问题标题】:Node JS Type Error : Cannot read property节点 JS 类型错误:无法读取属性
【发布时间】:2019-12-28 22:56:47
【问题描述】:

我是一名初学者 nodejs 开发人员,一开始我决定开发一个博客项目来练习。我在客户端上使用 Nodejs Express 和本机 js。添加帖子时,nodejs 在路由中抛出错误:
(节点: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)

可能是什么问题?

【问题讨论】:

  • 您是如何提出请求的?什么req.body
  • 我从客户端引用req到title字段,我想在express中处理。我可能是错的,做错事,所以问)

标签: javascript node.js express


【解决方案1】:

这是一个排序问题,把这几行调换一下:

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

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

【讨论】:

  • 非常感谢,折腾了半天,找错地方了
猜你喜欢
  • 2017-11-01
  • 2022-11-21
  • 1970-01-01
  • 2021-02-03
  • 2021-07-19
  • 2023-01-26
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多