node redirection
To achieve redirection in Node.js, you can make use of the HTTP
module's response
object. Here is a step-by-step explanation of how to perform redirection using Node.js:
- First, import the
HTTP
module by requiring it in your code:
const http = require('http');
- Create a server using the
createServer
method of thehttp
module:
const server = http.createServer((request, response) => {
// Your code here
});
- Inside the server's callback function, handle the incoming request and perform the necessary redirection. To redirect, set the
statusCode
property of theresponse
object to302
, which stands for "Found" or "Moved Temporarily". Also, set theLocation
header of the response to the target URL where you want to redirect the user:
response.statusCode = 302;
response.setHeader('Location', 'https://example.com');
- Finally, send the response to the client to complete the redirection:
response.end();
Here's the complete code snippet for redirecting a user in Node.js:
const http = require('http');
const server = http.createServer((request, response) => {
response.statusCode = 302;
response.setHeader('Location', 'https://example.com');
response.end();
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Remember to replace 'https://example.com'
with the target URL you want to redirect to.