![](/img/trans.png)
[英]Calling a variable to a different route not working in nodejs and express
[英]Check if variable is empty not working | NodeJS, Express
我正在尝试构建一个博客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请求:
所以我想知道为什么这不起作用,感觉就像一些明显的东西,但我无法让它工作。
谢谢阅读。
我不太了解Postman,但我猜测将body内容类型设置为raw
将body上传为text/plain
,这意味着body-parser
不会以任何方式解析它( console.log('body', typeof req.body)
将显示“body string” )。
相反,尝试将内容类型设置为application/json
(并确保您的服务器使用来自body-parser
的JSON中间件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.