Node.js / Express.js - redirecting requests

0 points
Created by:

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) => {
// 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) => {

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'.

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.

❤️💻 🙂