To redirect a page in Node.js, you can use the response.redirect()
method provided by the Express framework. This method takes in the URL of the page you want to redirect to as an argument.
Here's an example of how you can redirect a page in Node.js:
1 2 3 4 5 6 7 8 9 10 |
const express = require('express'); const app = express(); app.get('/redirect', (req, res) => { res.redirect('https://www.example.com'); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); |
In this example, when a GET request is made to the '/redirect' route, the server will redirect the user to 'https://www.example.com'.
You can also redirect to a specific route within your application by passing the route path as the argument to response.redirect()
.
What is the default status code used by res.redirect() in node.js?
The default status code used by res.redirect()
in Node.js is 302, which indicates a temporary redirect.
What is the difference between a 301 and 302 redirect in node.js?
In Node.js, a 301 redirect is a permanent redirect, meaning that the requested resource has been permanently moved to a new location. This status code tells search engines to update their indexed URLs and search results to the new location. On the other hand, a 302 redirect is a temporary redirect, indicating that the requested resource is temporarily moved to a different location. Unlike a 301 redirect, a 302 redirect does not update search engine indexed URLs and search results to the new location.
How to redirect a page with query parameters in node.js?
In Node.js, you can redirect a page with query parameters using the express
framework. Here's an example code snippet that demonstrates how to redirect a page with query parameters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const express = require('express'); const app = express(); const PORT = 3000; app.get('/redirect', (req, res) => { const queryParam = req.query.param; res.redirect(`/newpage?param=${queryParam}`); }); app.get('/newpage', (req, res) => { const queryParam = req.query.param; res.send(`Redirected to new page with query parameter: ${queryParam}`); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); |
In this code snippet, when a GET request is made to the /redirect
route with a query parameter (e.g. /redirect?param=value
), the server will redirect the request to the /newpage
route while preserving the query parameter. The redirected route will then retrieve the query parameter and display it in the response.
You can test this code by running the server and making a GET request to http://localhost:3000/redirect?param=value
. The server will redirect the request to http://localhost:3000/newpage?param=value
and display the message "Redirected to new page with query parameter: value".