In the previous sections, we've explored how to set up basic routes and handle different types of HTTP requests in Express.js. One common task when building web applications is sending JSON data as a response from an Express route. This tutorial will guide you through the process of sending JSON responses effectively.
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It's widely used in web applications to transmit data between the server and the client. Express.js provides a straightforward way to send JSON responses using the res.json() method.
Express.js automatically sets the Content-Type header to application/json when you use the res.json() method. This tells the browser or any other client that the response body contains JSON data. The res.json() method takes a JavaScript object or array and converts it into a JSON string before sending it as the response.
Let's dive into some practical examples to understand how to send JSON responses in Express.js.
Suppose you have an API endpoint that returns information about a user. Here's how you can do it:
1const express = require('express');2const app = express();3const port = 3000;45app.get('/user', (req, res) => {6const user = {7id: 1,8name: 'John Doe',9email: 'john.doe@example.com'10};1112res.json(user);13});1415app.listen(port, () => {16console.log(`Server is running on http://localhost:${port}`);17});
When you make a GET request to http://localhost:3000/user, the server will respond with the following JSON:
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}You can also send an array of objects as a JSON response. For instance, let's create an endpoint that returns a list of users:
1const express = require('express');2const app = express();3const port = 3000;45app.get('/users', (req, res) => {6const users = [7{ id: 1, name: 'John Doe' },8{ id: 2, name: 'Jane Smith' }9];1011res.json(users);12});1314app.listen(port, () => {15console.log(`Server is running on http://localhost:${port}`);16});
When you make a GET request to http://localhost:3000/users, the server will respond with:
[
{ "id": 1, "name": "John Doe" },
{ "id": 2, "name": "Jane Smith" }
]You can also specify a status code when sending JSON responses using the res.status() method followed by res.json(). For example:
1const express = require('express');2const app = express();3const port = 3000;45app.get('/user/:id', (req, res) => {6const userId = req.params.id;78if (userId === '1') {9const user = { id: 1, name: 'John Doe' };10return res.status(200).json(user);11}1213res.status(404).json({ message: 'User not found' });14});1516app.listen(port, () => {17console.log(`Server is running on http://localhost:${port}`);18});
In this example:
1, the server responds with a status code of 200 and the user object.1, the server responds with a status code of 404 and an error message.Now that you know how to send JSON responses, it's important to handle errors gracefully. The next section will cover Error-Handling Middleware in Express.js, which helps manage and respond to errors effectively.
By understanding these concepts, you'll be well-equipped to build robust APIs with Express.js that can communicate efficiently with clients using JSON data.