Easily create nodejs servers (6): Respond to nodejs servers
We then rebuild the server so that the request processing program can return some meaningful information.
Let's take a look at how to implement it:
1. Let the request processing program directly return () the information they want to display to the user through the onRequest function.
2. Let's start by asking the request handler to return the information that needs to be displayed in the browser.
We need to modify requestHandler. js to the following form:
Copy codeThe Code is 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, Request Routing must return the information returned by the request processing program to the server.
Therefore, we need to modify router. js to the following form:
Copy codeThe Code is 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 shown in the code above, when the request cannot be routed, we also return some related error messages.
Finally, we need to refactor our server. js so that it can respond to the browser through the content returned by the Request Routing, as shown below:
Copy codeThe Code is 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 (200, {"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 restructured 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 will output "404 Not found ".
This is a good idea. In the next section, we will learn about the concept of blocking operations.