Stat_prob_001
Stat_prob_001

Reputation: 181

Express is not reading the request body

I am new in node and express. So, I was learning how to do post request. When I learned, it was alright and it was creating another document in mangodb database. Today when I tried to do the same, this problem occurred.

enter image description here

I tried different things like removing required part in schema. But it seems express is failing to read req.body since when I send the request without any required fields in schema, it happily accepted and filled up default fields. I don't really understand what is happening. I was parallelly doing another project which is not giving this error.

PS. I am using mongoose@5.

Code to create tour:

exports.createTour = async (req, res) => {
  try {
    const newTour = await Tour.create(req.body);
    res.status(201).json({
      status: 'success',
      data: {
        tour: newTour,
      },
    });
  } catch (err) {
    res.status(404).json({
      status: 'fail',
      message: err.message,
    });
  }
};

Upvotes: 0

Views: 9973

Answers (2)

G-Mbeke
G-Mbeke

Reputation: 19

Make sure app.use(express.json()) is at the top of all your middlewares

// middleware 
app.use(express.json()) //Add it first then others follw

app.use(express.urlencoded({ extended: true }))

Upvotes: 2

jfriend00
jfriend00

Reputation: 707328

If the content-type for your POST is application/json, then you need this:

app.use(express.json())

as middleware before your POST request handler. That will read the JSON body of the request, parse it and put it in req.body.

Upvotes: 17

Related Questions