What are express.json() and express.urlencoded()?

What is Middleware

To understand what express.json and express.urlencoded do, you have to understand what middlewares are.

Middlewares are functions or methods in expressJS for carrying out various operations on requests made to the server.

By now you should know how to get a request to a route using express.

app.get("/api/houses", (req, res) => {
     console.log("Received request");
     res.send("houses")
   })

Importance of Middleware

The above code is a typical example of how express handles a get request. But in a situation whereby you want an operation to be carried on every request made to the server. You would not like to repeat codes in every route.

A middleware comes to the rescue at this stage. The middleware acts like a general reciever for every request.

app.use((req, res, next) => {
      console.log("Verifing request"); 
      next();
     })

The above is a custom middleware that verifies every request made to my server and sends ad sends the request too the next appropriate routeing middleware depending on the type of request it. (GET, POST, PUT etc.)

Builtin Middleware

Now expressJS has some already made middlewares which help developer in carrying out some tedious task. like converting request body to JSON and so many others.

Examples of these builtin ExpressJS middlewares are

  • express.json()
  • express.urlencoded()

express.json() is a built express middleware that convert request body to JSON.

express.urlencoded() just like express.json() converts request body to JSON, it also carries out some other functionalities like: converting form-data to JSON etc.