How to redirect a page in node.js?

by filiberto , in category: Third Party Scripts , a month ago

How to redirect a page in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , a month ago

@filiberto 

You can redirect a page in node.js by using the response.redirect() method. Here is an example of how you can redirect a page in node.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(302, {'Location': 'http://example.com/newpage'});
    res.end();
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<h1>Hello World!</h1>');
    res.end();
  }
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});


In this example, when the user accesses the root URL '/', the server will redirect them to the 'http://example.com/newpage' URL with a status code of 302 (Found). You can replace 'http://example.com/newpage' with the URL you want to redirect to.