DEV Community

RajeshKumarYadav.com
RajeshKumarYadav.com

Posted on • Updated on

Node.js : Hello World basic routing

Once you understand how to create an HTTP Server with node, it's important to understand how to make it "do"
things based on the path that a user has navigated to. This phenomenon is called, "routing".

The most basic example of this would be to check if (request.url === 'some/path/here'), and then call a function that responds with a new file.

An example of this can be seen here:

const http = require('http');
function index (request, response) {
 response.writeHead(200);
 response.end('Hello, World!');
}
http.createServer(function (request, response) {

 if (request.url === '/') {
 return index(request, response);
 }
 response.writeHead(404);
 response.end(http.STATUS_CODES[404]);
}).listen(1337);
Enter fullscreen mode Exit fullscreen mode

If you continue to define your "routes" like this, though, you'll end up with one massive callback function, and we don't want a giant mess like that, so let's see if we can clean this up.

First, let's store all of our routes in an object:

var routes = {
 '/': function index (request, response) {
 response.writeHead(200);
 response.end('Hello, World!');
 },
 '/foo': function foo (request, response) {
 response.writeHead(200);
 response.end('You are now viewing "foo"');
 }
}
Enter fullscreen mode Exit fullscreen mode

Now that we've stored 2 routes in an object, we can now check for them in our main callback:

http.createServer(function (request, response) {

 if (request.url in routes) {
 return routes[request.url](request, response);
 }
 response.writeHead(404);
 response.end(http.STATUS_CODES[404]);
}).listen(1337);
Enter fullscreen mode Exit fullscreen mode

Now every time you try to navigate your website, it will check for the existence of that path in your routes, and it will
call the respective function. If no route is found, the server will respond with a 404 (Not Found). And there you have it--routing with the HTTP Server API is very simple.

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Buy Me A Coffee

Top comments (0)