nodejs: redirect path to specific path
- Published
- Reading time
- 1 min read
- Length
- 251 words
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:
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:
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.