We then rebuilt the server so that the request handler could return some meaningful information.
Let's take a look at how to implement it:
1, let the request handler through the ONrequest function directly back (return ()) they want to show the user information.
2. Let's start by having the request handler return the information that needs to be displayed in the browser.
We need to modify the requesthandler.js into the following form:
Copy Code code as follows:
function Start () {
Console.log ("Request handler ' start ' was called.");
Return "Hello Start";
}
function upload () {
Console.log ("Request handler ' upload ' was called.");
Return "Hello Upload";
}
Exports.start = start;
Exports.upload = upload;
Similarly, a request route requires that the information returned to it by the request handler be returned to the server.
Therefore, we need to modify the router.js into the following form:
Copy Code code as follows:
function route (handle, pathname) {
Console.log ("About to route a request for" + pathname);
if (typeof handle[pathname] = = ' function ') {
return Handle[pathname] ();
} else {
Console.log ("No request handler found for" + pathname);
Return "404 Not Found";
}
}
Exports.route=route;
As the above code shows, we also return some related error messages when the request cannot be routed.
Finally, we need to refactor our server.js so that it can respond to the browser by asking for the content returned by the request route, as follows:
Copy Code code as follows:
var http = require ("http");
var url = require ("url");
function start (route, handle) {
function onrequest (request, Response) {
var pathname = Url.parse (request.url). Pathname;
Console.log ("Request for" + Pathname + "received.");
Response.writehead ({"Content-type": "Text/plain"});
var content = route (handle, pathname);
Response.Write (content);
Response.End ();
}
Http.createserver (ONrequest). Listen (8888);
Console.log ("Server has started.");
}
Exports.start=start;
If we run the refactoring after the application:
Request Http://localhost:8888/start, the browser will output "Hello start",
Request Http://localhost:8888/upload will output "Hello Upload",
The request Http://localhost:8888/foo output "404 Not Found".
This feels good, and in the next section we'll look at a concept: blocking operations.