Easily create nodejs server (6) : respond

  • 2020-05-07 19:10:59
  • OfStack

We then reconfigure the server so that the request handler returns some meaningful information.

Here's how to do it:

1. Have the request handlers directly return (return()) the information they are presenting to the user via the onRequest function.
2. Let's start by having the request handler return the information that needs to be displayed in the browser.

We need to modify requestHandler.js into the following form:


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, the request routing requires that the information returned to it by the request handler be returned to the server.
Therefore, we need to modify router.js into the following form:


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 code above shows, we also return some error messages when the request cannot be routed.
Finally, we need to refactor our server.js so that it can respond to the content returned by the request handler via the request route to the browser, as shown below:


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",
Request http: / / localhost: 8888 / upload will output "Hello Upload",
And request http: / / localhost: 8888 / foo will output "404 Not found".

That sounds good. In the next video we'll look at one concept: blocking operations.


Related articles: