In this blog post, we will learn how to serve JSON data using the Node.js Express library. When handling network requests with Express, a callback function is invoked on each request with a Request object instance and a Response object instance.
To demonstrate this, let’s consider the following example:
app.get('/', (req, res) => res.send('Hello World!'))
In the above example, we used the Response.send()
method to send a simple string response. However, if we want to send JSON data to the client, we can utilize the Response.json()
method, which is specifically designed for this purpose.
The Response.json()
method accepts an object or an array and automatically converts it to JSON format before sending it to the client. Here’s an example:
res.json({ username: 'Flavio' })
By calling Response.json({ username: 'Flavio' })
, we send a JSON object with the key-value pair { username: 'Flavio' }
to the client.
In summary, when serving JSON data in Express, we can use the Response.json()
method to easily send JSON objects or arrays to the client.
Tags: Express.js, JSON response, Node.js