首页 > 解决方案 > 验证后失败:标题:使用 nodejs 的 api 中需要路径“标题”

问题描述

// Creating one
router.post('/', async (req, res) => {
  const post = new Post({
    title: req.body.title,
    category: req.body.category,
    content: req.body.content,
    author: req.body.author,
    postDate: req.body.postdate,
    postTags: req.body.posttags
  })
  try {
    const newPost = await post.save()
    res.status(201).json(newPost)
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

我正在使用节点中的 API 服务器,但在从客户端请求 POS 调用后,响应是

验证后失败:标题:title需要路径。

mondoDB 的模型是

const mongoose = require('mongoose')

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  category:{
    type: String,
    required : true
  },
  content: {
    type: String,
    required: true
  },
  author :{
    type : String,
    required : true
  },
  postDate: {
    type: Date,
    required: true,
    default: Date.now
  },
  postTags : {
    type : Array,
    default : ["Coding"]
  }

})

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

标签: javascriptnode.jsapi

解决方案


鉴于您使用的是快递。这在应用程序初始化后进入主文件。这样您的应用程序就能够解析从前端接收到的 json 中的数据。

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

推荐阅读