express js redirect to url
To redirect to a URL using Express.js, you can use the redirect
method provided by the Express.js framework. Here are the steps to achieve this:
- First, make sure to import the Express.js module in your file:
const express = require('express');
const app = express();
- Next, define a route that will handle the redirect. This can be done using the
app.get
method, which sets up a route for HTTP GET requests:
app.get('/redirect', (req, res) => {
// Redirect logic goes here
});
- Inside the route handler function, use the
redirect
method to redirect to the desired URL. This method takes the URL as its argument:
app.get('/redirect', (req, res) => {
res.redirect('https://example.com');
});
- Finally, start the Express.js server to listen for incoming requests. This can be done using the
listen
method, which takes the port number as its argument:
app.listen(3000, () => {
console.log('Server started on port 3000');
});
With these steps, whenever a GET request is made to the /redirect
route, the server will redirect the user to the specified URL (https://example.com
in this example).
Note: Don't forget to replace 'https://example.com'
with the actual URL you want to redirect to.