我正在尝试构建一个博客 API,现在我的架构中有三个字段:
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 请求:
但错误表明我的 title
丢失了。但我正在传递我的标题 key 。
所以我想知道为什么这不起作用,感觉像是一些显而易见的东西,但我就是无法让它发挥作用。
感谢您的阅读。
最佳答案
我不太了解 Postman,但我猜测将正文内容类型设置为 raw
会将正文上传为 text/plain
,这意味着 body-parser
不会以任何方式解析它(console.log('body', typeof req.body)
将显示“body string”)。
相反,请尝试将内容类型设置为 application/json
(并确保您的服务器使用 body-parser
中的 JSON 中间件)。
关于javascript - 检查变量是否为空不起作用 | NodeJS、Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998847/