Express.js is a back-end web development library used in Node.js applications. It provides various tools and features that make the processes of developing the back-end of web applications more efficient as compared to using only Node.js.
express.json()
functionThe express.json()
function is a middleware function used in Express.js applications to
Suppose we have created an API that sends data in JSON format. Now, we will develop a web application that fetches data from the API for processing on the application server. How can we implement this in Express.js?
We would need to use the express.json()
function here, which would first receive the data from the API in JSON format and then parse the JSON string so its contents can be used and manipulated.
Now that we have understood the express.json()
function, let's look at how it parses the JSON data inside the web application.
Express.js applications essentially use a middleware that comprises middleware functions such as the express.json()
function that processes incoming requests to the express application.
When a client sends an HTTP request to the server with a JSON payload, the request is first passed through the application's middleware, where the express.json()
function converts the JSON string in the payload to a JSON object and populates the req.body
property with the parsed JSON, which can be assessed in the application using the req.body
object.
Once the application has finished processing the request, it usually sends back a response as an acknowledgment of the request.
Below are the steps that show us how to use the express.json()
middleware function in our express applications.
First, we have to create an Express.js application. A comprehensive guide to creating an Express.js application can be found here.
In the express app, we see that we first import the express module and then create its instance and store it in the app
variable, as shown below.
const express = require('express')const app = express()
We will now use the app.use()
function to configure our middleware, in which we will pass the express.json()
middleware function. So in our application, we will import the following line of code:
app.use(express.json())
Our back-end code would look like the following code snippet.
const express = require('express')const app = express()const port = 3000app.use(express.json())app.get('/', (req, res) => {res.send('Hello Educative User <3!')})app.post('/submit', (req, res) => {console.log('Received data:' req.body);// request manipulation here});app.listen(port, () => {console.log(`Listening on port ${port}`)})
In the final snippet, we have added the middleware function express.json()
in the sample application's code snippet. Any requests containing JSON strings sent to the server will be parsed to JSON objects.
If a user posts a JSON string to the submit
route, the data will be converted to a JSON object that can be accessed using the req.body
object.
Below, we can see a sample application that shows how we can use the express.json()
to convert JSON strings to JSON objects.
{ "name": "code", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2" } }
When we run the above application, we see a simple form is rendered with two input fields, name, and email. Once we enter the data into the fields and press the "Submit" button, we see that our form data, sent as a JSON string, is displayed in a JSON format in the "Terminal" tab.
In the index.js
file,
Line 6: We add the express.json()
middleware function to the application using the function app.use()
.
Line 8: Here, we add the express.static()
middleware function to serve static HTML files that are placed in the public
folder.
Lines 11–13: We define the home (/
) route in which we want to render the index.html
file located in the public
folder.
Lines 16–20: We define the submit
route that handles the form submission. Here, we print the JSON data parsed by the middleware using the req.body
object onto the console.
In the index.html
file inside the public
folder:
Lines 8–14: Here, we create a simple HTML form with two fields input fields, name and email, and a form submit button.
Lines 16–33: We add a script to transform the form data to a JSON string to send to the server as the payload for the request packet.
Line 18: We prevent the default browser submission for the form.
Lines 20–23: Now, we convert the form inputs to a JSON object named formData
.
Lines 25–31: We send an asynchronous HTTP POST request to the /submit
endpoint with the form data as a JSON string payload using the fetch
API. We use the JSON.stringify()
function to convert the JSON formData
object to a string.
Free Resources