Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js routes


May 10, 2021 Node.js


Table of contents


Node .js routes

We want to provide the URL of the request and other required GET and POST parameters for the route, and then the route needs to execute the appropriate code based on that data.

Therefore, we need to look at the HTTP request and extract the URL of the request and the GET/POST parameters. W hether this feature should belong to a route or a server (or even as a module's own) is certainly worth exploring, but here's a tentative function for our HTTP server.

All the data we need is included in the request object, which is passed as the first argument of the onRequest() callback function. B ut in order to parse this data, we .JS node modules, url and qurystring modules, respectively.

                   url.parse(string).query
                                           |
           url.parse(string).pathname      |
                       |                   |
                       |                   |
                     ------ -------------------
http://localhost:8888/start?foo=bar&hello=world
                                ---       -----
                                 |          |
                                 |          |
              querystring(string)["foo"]    |
                                            |
                         querystring(string)["hello"]

Of course, we can also use the qurystring module to parse the parameters in the POST request body, which will be demonstrated later.

Now let's add some logic to the onRequest() function to find out the URL path requested by the browser:

var http = require("http");
var url = require("url");

function start() {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

Well, our application can now distinguish between different requests by the URL path of the request -- which allows us to map the request to the handler using the route (which is not yet complete).

In the app we're building, this means that requests from /start and/upload can be handled using different code. W e'll see later how these things come together.

Now we can write the route, create a file called .js, and add the following:

function route(pathname) {
  console.log("About to route a request for " + pathname);
}

exports.route = route;

As you can see, this code does nothing, but it should be for now. B efore adding more logic, let's look at how to integrate routing and servers.

Our servers should be aware of the existence of routes and make effective use of them. Of course we can bind this dependency to the server in a hard-coded way, but programming experience in other languages tells us that this can be very painful, so we'll add routing modules more loosely using dependency injection.

First, let's extend the server's start() function to pass the routing function past as an argument:

var http = require("http");
var url = require("url");

function start(route) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    route(pathname);

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

At the same time, we extend the .js so that routing functions can be injected into the server:

var server = require("./server");
var router = require("./router");

server.start(router.route);

Here, the functions we pass still do nothing.

If you start the app now (node index.js and always remember the command line) and then request a URL, you'll see the app output the appropriate information, indicating that our HTTP server is already using the routing module and passing the path of the request to the route:

bash$ node index.js
Request for /foo received.
About to route a request for /foo

The above output has removed the more annoying /favicon .ico related to the request.