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:

  1. First, import the HTTP module by requiring it in your code:
const http = require('http');
  1. Create a server using the createServer method of the http module:
const server = http.createServer((request, response) => {
  // Your code here
});
  1. Inside the server's callback function, handle the incoming request and perform the necessary redirection. To redirect, set the statusCode property of the response object to 302, which stands for "Found" or "Moved Temporarily". Also, set the Location header of the response to the target URL where you want to redirect the user:
response.statusCode = 302;
response.setHeader('Location', 'https://example.com');
  1. 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.