Loading...

Routing in Node js

Routing in Node js

To understand the routing in node js, let’s first understand what do you mean by routing. Routing is the path in which client requests talk to applications’ endpoints. There are two ways in which routing can be implemented in node js, with Framework and without Framework. Many frameworks can be used with node js to run applications and servers but the most widely used one is Express.

Routing using Framework

The routing in Express takes place through an ‘app’ object which corresponds to the HTTP route. This app object performs two requests, get and post. Other methods are .put(), .delete(), .all()

Structure of routing: app.METHOD(PATH/URL, HANDLER/CALLBACK FUNCTION) where, 

  • The app is the instance object of express
  • METHOD is an ‘HTTP’ request method
  • URL is the path of the server
  • HANDLER is the function that is executed when the route matches the given path/URL 

For instance, take this URL as an example: http://codedamn.com/post/87/nodejs-preview-pdf?id=123&type=article

Now, this URL is broken down into several parts as mentioned above. 

Protocol: http

Hostname: codedamn.com

Pathname: /post/87/nodejs-preview-pdf

Search: ?id=123&type=article

Let us understand more about it using some methods and examples. 

GET request: The method used is app.get() and is used for getting a finite number of data as these data are sent into the header. Used to get data from URLs. For eg: app.get(‘/test’, function(req,res)) gets data from route where url=’/test’. 

var express = require('express')
var app = express()
app.get(‘/user’, function(req,res){
res.send(‘user profile’);
})

In this, the get method points to the given URL and sends the ‘user profile’ as a message/response. 

POST request: The method used is app.post() and is used for a larger amount of data from the server. It is usually used in posting data to servers for eg: in the submission of forms from application to server.

var express = require('express')
var app = express()
app.post(“/”, function(req,res){
// performs some function and the send some message
res.send(“completed”)
})

Code for handling all HTTP methods, for instance, GET, POST, DELETE, PUT use app.all() method:

var express = require('express')
var app = express()
app.all('/', function(req, res) {
console.log('HelloWorld!’)
next() // Pass the control to the next handler
})

The next() method is used to pass the control to the next callback function. Similarly, app.use() method is used to specify the middleware callback function. 

Steps for performing routing in Node js using Express Framework:
  • Load the express framework
  • Initialize the app object to express
  • Use app object to handle callback function

Here is the list of response methods that can be used on ‘res’:

Note that it depends on which framework are you using, express is most widely used with node js. 

Method Description of the method
res.download() The file to be downloaded is prompted 
res.json() Sends JSON object as a response
res.end() Terminates the process
res.jsonp() Sends a JSON response with the support of JSONP
res.redirect() Requests are being redirected to the specified URL
res.render() Renders a given template
res.send() Sends responses of different types
res.sendFile() Sends file as a stream
res.sendStatus() Sets the response code and sends it as a response

Routing without using any Framework

If you are using routing without framework then:

  • You are the one responsible for starting the server
  • Making routing decisions and reading URLs that are coming to the server
  • Perform necessary actions of incoming URLs 

Structure of URL: There are several parts that URL comprises of, here the some of the key ones

  • Protocol: HTTP or HTTPS 
  • Pathname: the path of URL
  • Hostname: server name
  • Search: query/string of the URL 

This routing is used when developers create their own servers. Here the built-in module of node js is used which is ‘HTTP’. Using a framework enhances the scalability and performance of the web application thereby saving time but it differs according to requirements. HTTP method can be found in the method property of the request object.

const server = http.createServer((request, response) => {
const method = request.method;
});

Copy the below code and paste it on any filename with extension ‘.js’. Here the module that would be used is ‘HTTP’ of node js.

Steps to be followed for routing without framework:

  • Load the module ‘HTTP’
  • Create server by using ‘HTTP’ module
  • Write callback function
  • Add action listener which is to be routed on port number 3000
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {‘Content-type’: ‘text/html’});
var url= req.url;
if(url==’/user’){

res.write(‘profile’);
res.end();
}
else if(url==’/contact){

res.write(‘contact page’);
res.end();
}
else if(url==’/about-us){

res.write(‘About Us page’);
res.end();
}
else{

res.write(‘Hello’);
res.end();
}
}).listen(3000, function() {

// Port 3000 is where the server object listens 
console.log("server start at port 3000");
});

When the URL redirects to ‘/user’ or ‘/contact’ or ‘/about-us’, it gives a response as given in res.write() and then ends the connection. If the URL redirects to something which is not mentioned in the if-else condition then it executes the else statement which then gives a response as ‘Hello’ given in res.write(). 

Conclusion

This was all about the routing in Node js, if you have any queries do drop it down in the comment box and check out courses on codedamn if you want to be a developer. Codedamn also has a playground to test different code with a built-in environment so do check it out. Join the developers’ community and check out articles on various different topics on codedamn.

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far