Languages
[Edit]
EN

Express.js - redirecting requests

0 points
Created by:
Mariam-Barron
781

In this article, we would like to show you how to redirect the user to a different URL in Express.js.

Quick solution

const express = require('express');
const app = express();

app.get('/request-path', (request, response) => {
  response.redirect('/target-path');
});
// 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.

Practical example

const express = require('express');

const port = 3000;
const app = express();

app.get('/example', (request, response) => {
  response.redirect('/another-path');
});

app.get('/another-path', (request, response) => {
  response.send('data from another path');
});

app.listen(port, () => {
    console.log(`server is listening at http://localhost:${port}`);
});

When the client sends get request to /example, will receive in response 'data from another path'.

Alternative titles

  1. Express.js - redirects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join