This article mainly introduces how to easily create nodejs servers (4): routing. servers need to perform different operations based on different URLs or requests. We can perform this step through routing, you can refer to the server to perform different operations based on different URLs or requests. We can perform this step through routing.
In the first step, we need to first parse the request URL path and introduce the url module.
Let's add some logic to the onRequest () function to find the URL path of the browser request:
The Code is as follows:
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 request path. We can use it to differentiate different requests, so that we can use different code to process requests from/start and/upload.
Next we will compile the route and create a file named router. js. The Code is as follows:
The Code is as follows:
Function route (pathname ){
Console. log ("About to route a request for" + pathname );
}
Exports. route = route;
This code has nothing to do. We first integrate routes with servers.
We then expand the server's start () function, run the routing function in start (), and pass the pathname as a parameter to it.
The Code is as follows:
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 expand index. js so that the routing function can be injected into the server:
The Code is as follows:
Var server = require ("./server ");
Var router = require ("./router ");
Server. start (router. route );
Run index. js and access any path, such as/upload, and you will find the console output, About to route a request for/upload.
This means that our HTTP server and Request Routing module can communicate with each other.
In the next section, we will provide different feedback for different URL requests.