Reputation: 6025
I am trying to build a blog API, and right now I have three fields in my schema:
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"]
}
})
I also have createPost
function, that is supposed to create a post (no shit):
// 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 })
})
}
I have those two if statements to check if the title or the content is empty, but that is not working. I tried to send a POST request with Postman:
But the error says that my title
is missing. But I am passing in my title key.
So I wonder why this is not working, it feels like some obvious stuff, but I just can't get this to work.
Thanks for reading.
Upvotes: 2
Views: 1328
Reputation: 203241
I don't know Postman too well, but I'm going to guess that setting the body content type to raw
uploads the body as text/plain
, which means body-parser
will not parse it in any way (console.log('body', typeof req.body)
will show "body string").
Instead, try setting the content type to application/json
(and make sure that your server uses the JSON middleware from body-parser
).
Upvotes: 3