Javascript
What are expressjson and expressurlencoded
Building robust web applications with Node.js and the Express.js framework often involves handling data sent from clients to the server. This incoming data, typically found in the request body of an HTTP POST or PUT request, needs to be parsed into a usable format by your server-side code. This is where two fundamental Express.js middleware functions, express.json() and express.urlencoded(), become indispensable. They act as translators, converting raw incoming request bodies into JavaScript objects that your application can easily work with. Understanding their specific roles and how to correctly implement them is crucial for any developer looking to manage diverse data submissions, from API requests carrying JSON payloads to traditional web forms sending URL-encoded data.
Understanding Middleware in Express.js
Before diving into the specifics of express.json() and express.urlencoded(), it’s essential to grasp the concept of middleware in Express.js. Middleware functions are like a series of checkpoints that every HTTP request passes through on its way to your route handlers. Each middleware function has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. They can execute code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function.
This modular approach allows developers to separate concerns, making applications more organized and maintainable. Common uses for middleware include logging requests, authenticating users, handling sessions, and, crucially, parsing incoming request bodies. When you use app.use() in your Express application, you’re essentially telling Express to apply that middleware to all incoming requests, or to specific paths if you define them. This powerful pattern forms the backbone of how Express applications process data and manage their lifecycle.
How Middleware Works
Think of middleware as a pipeline. When a request comes in, it enters one end of the pipeline. Each piece of middleware performs its task and then, if it doesn’t terminate the request, passes it along to the next piece. For instance, an authentication middleware might check for a valid token; if one isn’t present, it might send a 401 Unauthorized response and stop the request from proceeding further. If the token is valid, it might attach user information to the req object and call next(), allowing the request to move to the next middleware or the final route handler. This sequential execution ensures that requests are processed systematically and efficiently, preparing the data for your business logic.
Deep Dive into express.json()
The express.json() middleware is specifically designed to parse incoming request bodies with JSON (JavaScript Object Notation) payloads. In the modern landscape of web development, particularly with RESTful APIs and single-page applications (SPAs), JSON has become the de facto standard for data interchange due to its simplicity and readability. When a client sends data to your Express.js server with the Content-Type header set to application/json, express.json() steps in to parse this raw JSON string into a JavaScript object, which is then made available on the req.body property of the request object.
Without express.json(), the req.body property would be undefined, making it impossible to access the data sent in the request body. This middleware is crucial for handling JSON data efficiently. It’s typically applied globally in an Express application using app.use(express.json()). For example, if a client sends { "username": "jane.doe", "email": "jane@example.com" } as a JSON string in the request body, after passing through express.json(), your route handler can access this data as req.body.username and req.body.email.
A common use case for express.json() is in API development. Imagine building an API for a blog platform where clients send new post data, user registration details, or comments as JSON. express.json() ensures that your server can correctly interpret and process these structured data submissions. It also includes options for configuration, such as setting a limit to prevent excessively large JSON payloads, which can be a security concern, or a strict option to only accept arrays and objects.
Deep Dive into express.urlencoded()
In contrast to express.json(), the express.urlencoded() middleware is used to parse incoming request bodies that are URL-encoded. This format is traditionally used by HTML forms when they submit data to a server. When an HTML form is submitted with the default enctype="application/x-www-form-urlencoded", the data is sent as a query string in the request body, where key-value pairs are separated by & and spaces are replaced by + (or %20). express.urlencoded() parses this string into a JavaScript object, making it accessible via req.body.
Similar to express.json(), without express.urlencoded(), form data would not be automatically parsed, and req.body would remain undefined. This middleware is vital for applications that interact with traditional web forms. It also supports an extended option, which, when set to true, allows for rich objects and arrays to be encoded into the URL-encoded format, using the “qs” library for parsing. If set to false, it uses the simpler “querystring” library, which only supports simple key-value pairs.
For example, if a web form submits data like name=John+Doe&age=30, after passing through express.urlencoded({ extended: true }), your route handler would find req.body.name as “John Doe” and req.body.age as “30”. This is particularly useful for handling user registrations, contact forms, or any scenario where information is gathered through standard HTML form submissions. The extended: true option is generally recommended as it allows for more flexible data structures, aligning with modern web development needs, and is the default in newer Express versions.
Choosing the Right Parser: Best Practices and Considerations
The decision to use express.json() or express.urlencoded(), or both, depends entirely on the type of data your Express.js application expects to receive. Many modern applications, especially those built around REST APIs, primarily deal with JSON data, making express.json() the go-to choice. However, if your application also serves traditional web pages with forms, express.urlencoded() becomes equally important. It’s common practice to use both middleware functions in an Express application if it needs to handle both types of incoming request bodies. When both are used, Express will attempt to Question & Answer :
I cannot find any documentation on express.json() and express.urlencoded(). What do each of them do exactly?
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 }));