In Node.js express, to redirect to a new page, use the res.redirect() method. This method is part of the response object in Express:
app.get('/old-route', (req, res) => {
res.redirect('/new-route');
});
In a Node.js application using Express, you can redirect a client to a new URL using the res.redirect() method. This method is part of the response object in Express and is used to send an HTTP redirect response to the client.
Here's a basic example of how you can use res.redirect():
const express = require('express');
const app = express();
app.get('/', (req, res) => {
// Redirect to a different URL
res.redirect('https://www.example.com');
});
// You can also use res.redirect with a status code
// For example, a 301 Moved Permanently redirect
app.get('/old-route', (req, res) => {
res.redirect(301, '/new-route');
});
app.get('/new-route', (req, res) => {
res.send('This is the new route.');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
res.redirect(url): This will send a 302 Found status code by default, indicating that the resource resides temporarily under a different URI.res.redirect(statusCode, url): You can specify a particular status code, such as 301 (Moved Permanently), 302 (Found), 303 (See Other), or 307 (Temporary Redirect), depending on the type of redirect you want to perform.By using these methods, you can control how and where to direct the client to a new URL when they access specific routes in your Express application.