Express JS redirects and status codes
In Express.js, redirects and status codes are crucial for managing the flow of HTTP responses and guiding client behavior. Here's an in-depth explanation of how to handle redirects and status codes in Express.js:
Redirects in Express.js
Redirects are used to send a client to a different URL. This is often done when a resource has moved or to direct users to different parts of the application.
Basic Redirect
To redirect a client to a different URL, use the res.redirect()
method.
Syntax:
res.redirect([status,] path);
status
(optional): HTTP status code for the redirect. Defaults to302
if not specified.path
: The URL to redirect to.
Example:
const express = require('express');
const app = express();
app.get('/old-page', (req, res) => {
res.redirect('/new-page'); // Redirects to '/new-page' with a 302 status code
});
app.get('/new-page', (req, res) => {
res.send('Welcome to the new page!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, a request to /old-page
will be redirected to /new-page
.
Redirect with Status Code
You can specify the HTTP status code for the redirect. Common status codes for redirects include:
301
: Moved Permanently302
: Found (Temporary Redirect)303
: See Other307
: Temporary Redirect308
: Permanent Redirect
Example:
app.get('/permanent-move', (req, res) => {
res.redirect(301, '/new-location'); // Redirects permanently to '/new-location'
});
Here, a request to /permanent-move
will be redirected to /new-location
with a 301
status code, indicating that the resource has been permanently moved.
Redirecting to External URLs
You can also redirect to an external URL:
Example:
app.get('/external', (req, res) => {
res.redirect('https://www.example.com'); // Redirects to an external URL
});
A request to /external
will redirect the client to https://www.example.com
.
Status Codes in Express.js
HTTP status codes are sent by the server to indicate the outcome of the client’s request. They are essential for communicating whether a request was successful, encountered an error, or requires further action.
Sending Status Codes
You can set the HTTP status code for a response using res.status()
. This method sets the status code for the response but does not send the response immediately. You still need to call res.send()
, res.json()
, or another method to complete the response.
Syntax:
res.status(statusCode);
Example:
app.get('/success', (req, res) => {
res.status(200).send('Request was successful'); // Sends a 200 OK response
});
app.get('/error', (req, res) => {
res.status(500).send('Internal Server Error'); // Sends a 500 Internal Server Error response
});
In this example:
/success
returns a200 OK
status with a success message./error
returns a500 Internal Server Error
status with an error message.
Common Status Codes
- 200 OK: The request was successful.
- 201 Created: The request was successful and resulted in the creation of a resource.
- 204 No Content: The request was successful, but there is no content to send in the response.
- 301 Moved Permanently: The requested resource has been moved permanently to a new URL.
- 302 Found: The requested resource has been temporarily moved to a different URL.
- 400 Bad Request: The server could not understand the request due to invalid syntax.
- 401 Unauthorized: The request requires user authentication.
- 403 Forbidden: The server understood the request but refuses to authorize it.
- 404 Not Found: The requested resource could not be found.
- 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
Using Status Codes for Error Handling
You can use status codes to handle errors gracefully and provide meaningful responses to the client.
Example:
app.get('/not-found', (req, res) => {
res.status(404).send('Page not found'); // Sends a 404 Not Found response
});
app.get('/forbidden', (req, res) => {
res.status(403).send('Access denied'); // Sends a 403 Forbidden response
});
In these examples:
/not-found
returns a404 Not Found
status when the resource is not available./forbidden
returns a403 Forbidden
status when access to the resource is denied.
Summary
- Redirects: Use
res.redirect()
to guide the client to a different URL. You can specify the status code for the redirect and redirect to internal or external URLs. - Status Codes: Use
res.status()
to set the HTTP status code for the response. This communicates the outcome of the request to the client. Common status codes include200
,404
, and500
, among others.