Express JS sending response
In Express.js, sending responses back to the client is an essential part of handling HTTP requests. You can send responses in various formats, including plain text, JSON, or HTML, depending on the nature of the response and the type of client consuming it (browser, API client, etc.).
1. Sending Text Responses
Express allows you to send plain text as a response using the res.send()
method.
Example of Sending Plain Text
const express = require('express');
const app = express();
app.get('/text', (req, res) => {
res.send('This is a plain text response'); // Sends plain text response
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, when a client makes a GET request to /text
, the server responds with the text:
This is a plain text response
2. Sending JSON Responses
JSON (JavaScript Object Notation) is commonly used for APIs and data exchange. Express provides a res.json()
method to send a JSON response.
Example of Sending JSON
app.get('/json', (req, res) => {
const data = {
message: 'This is a JSON response',
success: true
};
res.json(data); // Sends a JSON response
});
When a client makes a GET request to /json
, the server responds with a JSON object:
{
"message": "This is a JSON response",
"success": true
}
- The
res.json()
method automatically sets theContent-Type
header toapplication/json
.
3. Sending HTML Responses
To send HTML content as a response, you can use the res.send()
method just like with plain text, but include HTML content in the response.
Example of Sending HTML
app.get('/html', (req, res) => {
res.send(`
<html>
<head>
<title>HTML Response</title>
</head>
<body>
<h1>Hello, this is an HTML response!</h1>
</body>
</html>
`); // Sends an HTML response
});
When a client makes a GET request to /html
, the response would be rendered as an HTML page in the browser:
<html>
<head>
<title>HTML Response</title>
</head>
<body>
<h1>Hello, this is an HTML response!</h1>
</body>
</html>
The client (usually a browser) will interpret this as an HTML document and render it accordingly.
4. Sending a File as a Response
Express also allows you to send files as responses using the res.sendFile()
method. This is useful for serving files like images, documents, or even static HTML pages.
Example of Sending a File
const path = require('path');
app.get('/file', (req, res) => {
const filePath = path.join(__dirname, 'example.pdf'); // Path to the file
res.sendFile(filePath); // Sends a file as a response
});
When the client makes a GET request to /file
, the server sends the example.pdf
file as a response for download or display in the browser.
5. Setting Status Codes
You can also specify the HTTP status code for the response using res.status()
before sending the actual response.
Example with Status Code
app.get('/not-found', (req, res) => {
res.status(404).send('Resource not found'); // Sends a 404 status code with a text response
});
In this case, the server will respond with:
404 Resource not found
6. Chaining Status Codes and Responses
You can chain res.status()
with other response methods like res.send()
, res.json()
, or res.sendFile()
.
Example of Chaining
app.get('/error', (req, res) => {
res.status(500).json({
error: 'Internal Server Error',
success: false
}); // Sends a 500 status code and a JSON response
});
When a client makes a GET request to /error
, the server responds with:
{
"error": "Internal Server Error",
"success": false
}
7. Redirecting Responses
Express allows you to redirect clients to another URL using res.redirect()
. This is useful when you need to send users to a different page or endpoint.
Example of Redirecting
app.get('/redirect', (req, res) => {
res.redirect('/new-location'); // Redirects the client to '/new-location'
});
8. Setting Response Headers
You can set custom headers for your responses using the res.set()
method.
Example of Setting Headers
app.get('/headers', (req, res) => {
res.set('Custom-Header', 'This is a custom header');
res.send('Headers set');
});
This sets a custom header called Custom-Header
in the response.
9. Conclusion
Express.js provides flexible methods to send responses to clients, including:
res.send()
for sending text, HTML, or files.res.json()
for sending JSON responses, ideal for APIs.res.sendFile()
for sending files to the client.res.status()
for specifying HTTP status codes.res.redirect()
for redirecting to different routes.