Redirecting requests in Node.js


Now we have an App.js file shown below, we want to redirect the user back to ‘/’ once user name is received by node server. We will store user name in a file named username.txt

Initial App.js file −

const http = require('http');
const server = http.createServer((req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/>       <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello </body>');
   res.write('</html>');
   res.end();
});
server.listen(3000);

We added below if block which consists the redirection .

First added file system module using const fs = require('fs'); File system fs module gives us writeFile and writeFileSync method to write content to file. As of now we are only writing a test value to file. Later we will see how to write value from request.

First added file system module using const fs = require('fs'); File system fs module gives us writeFile and writeFileSync method to write content to file. As of now we are only writing a test value to file. Later we will see how to write value from request.

if(url === '/username' && req.method === 'POST'){
   fs.writeFileSync('username.txt', 'test value');
   //redirect
   res.statusCode=302;
   res.setHeader('Location','/');
   return res.end();
}

Http redirect status code is 302. ‘Location’ is also a header which is set in response. Location header is pointing to url ‘/’. This is where the response will be redirected to.

  • User input output screen

  • After redirection, we will be back to same page with a file created in project directory .

Complete updated App.js file is −

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/>       <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
   if(url === '/username' && req.method === 'POST'){
      fs.writeFileSync('username.txt', 'test value');
      //redirect
      res.statusCode=302;
      res.setHeader('Location','/');
      return res.end();
   }
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello </body>');
   res.write('</html>');
   res.end();
});
server.listen(3000);

Updated on: 13-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements