检查variables是否为空不工作| NodeJS,Express
我正在尝试构build博客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
函数,这是应该创build一个职位(没有狗屎):
// 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语句来检查标题或内容是否为空,但这是行不通的。 我试图发送POST邮件POST请求:
但错误说我的title
丢失了。 但是我传递了我的标题密钥。
所以我想知道为什么这不起作用,感觉就像一些明显的东西,但我不能得到这个工作。
谢谢阅读。
我不太了解邮递员,但是我猜测将body的内容types设置为raw
将body以text/plain
方式上传,这意味着body-parser
不会以任何方式parsing它( console.log('body', typeof req.body)
会显示”body string“ )。
相反,尝试将内容types设置为application/json
(并确保您的服务器使用body-parser
的JSON中间件)。