This tutorial demonstrates redirecting the users in Node.js application without relying on the express . Express framework can handle the redirect through the built-in methods. We will achieve this in Node.js by using the native “http” module.
Redirect in Node.js:
To demonstrate how to perform redirect in Node.js , we will use the basic http server that listens requests and redirects from one path to another.
Below is the code for server.js :
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/old-page') { res.writeHead(302, { Location: '/new-page' }); res.end(); } else if (req.url === '/new-page') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('You are redirected to a new page.'); res.end(); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('Page not found.'); res.end(); } }); server.listen(3000, () => { console.log('Server listening on port 3000'); });
Explanation :
Step 1 : Import the http module
To create a http server , we need to import the built-in “http” module.
const http = require('http');
Step 2 : Create the server
We create an http server using the “http.createServer” method. This server listens to the incoming requests and gives response based on the request URL.
const server = http.createServer((req, res) => {
Step 3 : Handling redirect
if (req.url === '/old-page') { res.writeHead(302, { Location: '/new-page' }); res.end();
When the server receives a request URL for the “old-page” , it temporarily redirects to the “new-page”.
302 (Status code) represents Found and it temporarily redirects.
} else if (req.url === '/new-page') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('You are redirected to a new page.'); res.end();
When the server receives a request for “new-page” , it displays the message .
200 (Status code) represents OK .
} else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('Page not found.'); res.end(); } });
When the server receives requests other than the path mentioned above , it will display “Page not found.”
404 (Status code) represents NOT FOUND.
Step 4 : Start the server
server.listen(3000, () => { console.log('Server listening on port 3000'); });
The server will be listening at the port 3000 and the callback function logs a message indicating that the server is running.
Step 5 : Run the application
Run the server by executing the following command :
node server.js
Conclusion :
This tutorial demonstrated how to redirect in Node.js without using Express. By understanding how to use the native “http” module, you can perform basic routing and redirection tasks effectively in Node.js.
References :
Node.js Http module documentation Click here for the documentation