Skip to content
the poor coder

nodejs: redirect path to specific path

Poor Man
Published
Reading time
1 min read
On this page

Node.js: Redirect Path to Specific Path#

Redirecting a path to a specific path in Node.js can be achieved using the redirect() method of the response object. This method sends a 302 HTTP status code and a Location header to the client, which instructs the client to access the specified URL instead.

Using Express.js#

If you are using the popular Express.js framework, you can simply use the redirect() method in your route handler function to redirect the path to a specific path. Here is an example:

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

// the route handler function
app.get('/old-path', (req, res) => {
  res.redirect('/new-path');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

In this example, when someone accesses the URL /old-path, they will be redirected to /new-path.

Using Vanilla Node.js#

If you are not using any framework and want to redirect a path to a specific path in plain Node.js, you can use the response.writeHead() and response.end() methods to send the necessary headers and end the response. Here is an example:

Text
const http = require('http');

const server = http.createServer((request, response) => {
  if (request.url === '/old-path') {
    response.writeHead(302, { 'Location': '/new-path' });
    response.end();
  } else {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello World!');
  }
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

In this example, when someone accesses the URL /old-path, they will receive a 302 status code and a Location header that instructs the client to access /new-path instead.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC