2

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: enter image description here

But the error says that my title is missing. But I am passing in my title key. enter image description here

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.

2
  • 1
    it seems to me that req.body is just a string and referring req.body.title gets you then undefined which causes the jump into the if block Commented Sep 1, 2017 at 11:07
  • 1
    Make sure you have installed and enabled the body-parser middleware (or one with similar functionality). EDIT: And set Postman to use application/json for the Content-Type header :) Commented Sep 1, 2017 at 11:08

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

You're right! This was a silly mistake! I changed it to x-www-form-urlencoded and now I'm seeing my error message! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.