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

Javascriptnode.jsExpress

Javascript Problem Overview


I cannot find any documentation on express.json() and express.urlencoded(). What do each of them do exactly?

Javascript Solutions


Solution 1 - Javascript

Here is the explanation that should clear doubts on express.json() and express.urlencoded() and the use of body-parser. It took me some time to figure this out.

  1. What is Middleware? It is those methods/functions/operations that are called BETWEEN processing the Request and sending the Response in your application method.

  2. When talking about express.json() and express.urlencoded() think specifically about POST requests (i.e. the .post request object) and PUT Requests (i.e. the .put request object)

  3. You DO NOT NEED express.json() and express.urlencoded() for GET Requests or DELETE Requests.

  4. You NEED express.json() and express.urlencoded() for POST and PUT requests, because in both these requests you are sending data (in the form of some data object) to the server and you are asking the server to accept or store that data (object), which is enclosed in the body (i.e. req.body) of that (POST or PUT) Request

  5. Express provides you with middleware to deal with the (incoming) data (object) in the body of the request.

a. express.json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object. This method is called as a middleware in your application using the code: app.use(express.json());

b. express.urlencoded() is a method inbuilt in express to recognize the incoming Request Object as strings or arrays. This method is called as a middleware in your application using the code: app.use(express.urlencoded());

  1. ALTERNATIVELY, I recommend using body-parser (it is an NPM package) to do the same thing. It is developed by the same peeps who built express and is designed to work with express. body-parser used to be part of express. Think of body-parser specifically for POST Requests (i.e. the .post request object) and/or PUT Requests (i.e. the .put request object).

  2. In body-parser you can do

    // calling body-parser to handle the Request Object from POST requests
    var bodyParser = require('body-parser');
    // parse application/json, basically parse incoming Request Object as a JSON Object 
    app.use(bodyParser.json());
    // parse application/x-www-form-urlencoded, basically can only parse incoming Request Object if strings or arrays
    app.use(bodyParser.urlencoded({ extended: false }));
    // combines the 2 above, then you can parse incoming Request Object if object, with nested objects, or generally any type.
    app.use(bodyParser.urlencoded({ extended: true }));
    

Solution 2 - Javascript

The json and urlencoded middleware are both part of bodyParser. This is what the README says:

> ### bodyParser([options]) > Returns middleware that parses both json and urlencoded. The options are passed to both middleware.

>### bodyParser.json([options])

>Returns middleware that only parses json. The options are:

>- strict - only parse objects and arrays

  • limit <1mb> - maximum request body size
  • reviver - passed to JSON.parse()

>### bodyParser.urlencoded([options])

>Returns middleware that only parses urlencoded with the qs module. The options are:

>- limit <1mb> - maximum request body size

Solution 3 - Javascript

If you ask me "what is the difference between express.urlencoded({extended: false}) and express.json()"

well, the difference is

if you use express.json() it will parse the body from post/fetch request except from html post form

it wont parse information from the html post form

<form action="/" method="POST">
    <input type="text" name="username">
    <button>Submit</button>
</form>

for instance, if you fill the form with "dean_ilham" then submit it, express wont have an idea what inside the body.

with express code :

const express = require('express')
const app = express()

app.use(express.json())
// app.use(express.urlencoded({ extended: false }))
app.use(express.static("public"))


app.get("/", (req, res) => {
    res.sendFile("index.html")
})

app.post("/", (req, res) => {
    res.send(req.body)
})


const port = process.env.PORT || 3001
app.listen(port, () => {
    console.log(`Server Up in Port ${port}`);
})

it will send {} after you click submit.

but if you uncommented app.use(express.urlencoded({extended: false})), then you will get {"username": "dean_ilham"}

so the difference is express.json() is a body parser for post request except html post form and express.urlencoded({extended: false}) is a body parser for html post form

Solution 4 - Javascript

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.

Solution 5 - Javascript

This middleware is available in Express v4.16.0 onwards.

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

extended[boolean]: This option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded

express docs :- https://expressjs.com/en/api.html#express.urlencoded

Solution 6 - Javascript

express.urlencoded() is required when you are submitting a form with post method ( default content-type = application/ x-www-form-urlencoded ) and you need to acess that form data using req.body , if you don't use it req.body would be undefined.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3450695View Question on Stackoverflow
Solution 1 - JavascriptKean AmaralView Answer on Stackoverflow
Solution 2 - JavascriptPaulView Answer on Stackoverflow
Solution 3 - Javascriptme noobView Answer on Stackoverflow
Solution 4 - JavascriptJoelView Answer on Stackoverflow
Solution 5 - JavascriptMohammed SaeidView Answer on Stackoverflow
Solution 6 - JavascriptPrashant JoshiView Answer on Stackoverflow