What are express.json() and express.urlencoded()?
I cannot find any documentation on express.json()
and express.urlencoded()
. What do each of them do exactly?
Solution 1:
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.
What is Middleware? It is those methods/functions/operations that are called BETWEEN processing the Request and sending the Response in your application method.
When talking about
express.json()
andexpress.urlencoded()
think specifically about POST requests (i.e. the .post request object) and PUT Requests (i.e. the .put request object)You DO NOT NEED
express.json()
andexpress.urlencoded()
for GET Requests or DELETE Requests.You NEED
express.json()
andexpress.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-
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());
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).
-
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:
The json
and urlencoded
middleware are both part of bodyParser. This is what the README says:
bodyParser([options])
Returns middleware that parses both
json
andurlencoded
. Theoptions
are passed to both middleware.bodyParser.json([options])
Returns middleware that only parses
json
. The options are:
strict
- only parse objects and arrayslimit
<1mb> - maximum request body sizereviver
- passed toJSON.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:
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:
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.