Hello World basic routing

suggest change

Once you understand how to create an HTTP server with Node, the next step is to choose a response from the path the client requested. That is routing.

request.url is the path plus the query string, with no origin. http://localhost:1337/foo?x=1 yields /foo?x=1, so a check against '/foo' does not match while a query string is present.

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

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"');
    }
}

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

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents