Routing requests in Node.js

Node.jsServer Side ProgrammingProgramming

Routing http requests is important because we want to execute different business rules based on request url and the responses will be different for each routes.

Earlier we saw, we can get the url by request.url in node. Simple example of user name input with routes is shown below −

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="user"/>
      <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
});
server.listen(3000);

Run it on terminal: node App.js

Open browser and navigate to localhost:3000/ you will see below output −

We checked if url is matching with ‘/’, then only sending a response to display a input box with submit button to client. Here in code, we used return res.end() to avoid any change in response object once end() function is called.

If the url is different than just ‘/’ then we can display other messages. We used form action ‘/username’ and method is post. Also we have input box with name attribute as user. This name attribute will be passed in the post request for further use.

Complete App.js file is −

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);

The outputs screen once username is entered and send is clicked −

We can see here, the url is changed to /username, it is because we added form action in earlier response.

In the second res.end(), we have not added a return statement because there is no code after that so we don’t need to bother about it.

With url /username, our code does not execute the if block containing code for form input but instead will execute the code below the if block.

raja
Published on 13-May-2020 15:08:13
Advertisements