我想建立一个博客API,而现在我已经在我的架构三个方面:检查变量是否为空不工作|的NodeJS,快速
const PostSchema = new Schema({
timestamp: {
type: Date,
default: Date.now
},
title: {
type: String,
required: [true, "Title is required"]
},
content: {
type: String,
required: [true, "Content is required"]
}
})
我也有createPost
功能,就是为了建立一个后(没有狗屎):
// Create post
const createPost = (req, res, next) => {
const title = req.body.title
const content = req.body.content
console.log('body', req.body) // getting output
if (!title) {
res.status(422).json({ error: "Titel saknas!!!" })
}
if (!content) {
res.status(422).json({ error: "Skriv något för fan!" })
}
const post = new Post({
title,
content
})
post.save((err, post) => {
if (err) {
res.status(500).json({ err })
}
res.status(201).json({ post })
})
}
我有这两个if语句来检查标题或内容是否为空,但这是行不通的。我试图发送Postman的POST请求:
所以我想知道为什么这不起作用,感觉就像一些明显的东西,但我无法得到这个工作。
感谢您的阅读。
在我看来,req.body只是一个字符串,而引用req.body.title让你然后undefined导致跳进if块 – Kristianmitk
确保你已经安装并启用了'body-parser'中间件(或者具有类似功能的一个)。编辑:并设置邮递员使用'应用程序/ json'为内容类型标题:) – damd