What does express.urlencoded do anyway?
What does express.urlencoded do anyway?
Nikhil Vijayan
·
Follow
·
Aug 14, 2021
1 min read
—
I finally found out what this bit of middleware in most express apps does, and wanted to document it
app.use(
express.urlencoded({
extended: true,
})
);
The documentation says:
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Returns middleware that only parses JSON and only looks at requests where the
Content-Type
header matches thetype
option. This parser accepts any Unicode encoding of the body and supports automatic inflation ofgzip
anddeflate
encodings.A new
body
object containing the parsed data is populated on therequest
object after the middleware (i.e.req.body
), or an empty object ({}
) if there was no body to parse, theContent-Type
was not matched, or an error occurred.
👆This makes very little sense to me, but I want to thank Deepal Jayasekara for clarifying this as:
✅ express.urlencoded middleware is used only for parsing request body of content-type x-www-form-urlencoded
For eg: Assuming you have an app running on port 8080, and you have a request like this:
You will only be able to access req.body.foo
if you have the express.urlencoded
middleware.
BTW, if you’re still using body-parser
to do this, note that it has been deprecated and express encourages you to use express.json()
and express.urlencoded
methods that come with express now.