Easily create nodejs server (4) : routing

  • 2020-05-07 19:11:09
  • OfStack

The server needs to perform different operations based on different URL or requests, and we can do this step by route.

Step 1 we need to resolve the path to request URL. We introduce the url module.

Let's add some logic to the onRequest() function to find 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, pathname is the path of the request, and we can use it to distinguish between requests, so that we can use different code for requests from /start and /upload.

Next, we will write the route and create a file named router.js. The code is as follows:


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

This code doesn't do anything. Let's integrate the routing and server.

We then extend the server's start() function, run the routing function in start(), and pass pathname as an argument to it.


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 will extend index.js accordingly, so that the routing function can be injected into the server:


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

Run index.js, access any path, such as /upload, and you'll find the console output, About to route a request for /upload.

This means that our HTTP server and the request routing module can already communicate with each other.

In the next section we will implement different responses to different URL requests.


Related articles: