We then transform the server so that the request handler can return some meaningful information.
Let's see how to implement it:
1. Let the request handler directly return (return()) the information they want to display to the user through the onRequest function.
2. Let's start by letting the request handler return the information that needs to be displayed in the browser.
We need to modify requestHandler.js to the following form:
The code copy 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 requires the information returned by the request handler to it to the server.
Therefore, we need to modify router.js to the following form:
The code copy 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 above code, when the request cannot be routed, we also return some related error messages.
Finally, we need to refactor our server.js to enable it to respond to the content returned by the request handler through the request route to the browser, as shown below:
The code copy 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 refactored application:
Request http://localhost:8888/start, the browser will output "Hello Start".
Requesting http://localhost:8888/upload will output "Hello Upload".
When requesting http://localhost:8888/foo, it will output "404 Not found".
This feels good, and we will learn about a concept in the next section: blocking operations.