EN
Express.js - redirecting requests
0 points
In this article, we would like to show you how to redirect the user to a different URL in Express.js.
xxxxxxxxxx
1
const express = require('express');
2
const app = express();
3
4
app.get('/request-path', (request, response) => {
5
response.redirect('/target-path');
6
});
7
// some code...
In response to the GET request to the specified path, the server executes the redirect method, which takes the redirect path as an argument and replies with the status 302.
xxxxxxxxxx
1
const express = require('express');
2
3
const port = 3000;
4
const app = express();
5
6
app.get('/example', (request, response) => {
7
response.redirect('/another-path');
8
});
9
10
app.get('/another-path', (request, response) => {
11
response.send('data from another path');
12
});
13
14
app.listen(port, () => {
15
console.log(`server is listening at http://localhost:${port}`);
16
});
When the client sends get request to /example
, will receive in response 'data from another path'
.