Routing Requests and Structuring Node Response Handlers

So, I am a system programmer who is currently teaching web application programming. As always, when you are learning something new, I am still not firmly versed in idiomatic implementations or simply set how to do something “right”.

After some time creating several games and a trivial user interface using only HTML and javascript, I now exit into a non-trivial dynamic application. I use Node as my server and ask a question about how to redirect response handlers.

I follow the (apparently) wonderful guide found here . This is the only reference I have found so far that allows you to create a real application (as opposed to something like response.write("Hello world"); response.end();).

The author suggests adding response handlers like this:

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

The code should be understandable, but essentially it uses the object as an associative container to map the resource requested in the query string to the handler. This is good and good, but I would not want to add a line to this file every time I add a new handler.

My idea was this; create a module for each handler and use some common interface to process the response. Sort of:

function handleReq(...) {
    ...
}

exports.handleRequest = handleReq;

I could then just requiremodule dynamically, i.e.

// in my router module
function route(pathName, args) {
    // where 'pathName' is something obtained
    // in a manner like so in the request handler:
    // url.parse(request.url).pathname;  

    var handler = require(pathName);
    handler.handleRequest(args);
}

- , ? , , , /, . , , , , , , - .

. , , , .

+2
1

, , .

: , , , , ... - . moduleName.handleRequest(scriptName, req, resp); true, . ( , , true, 404)

scriptName , ( "/start" "start" ..), , , , , .

- :

var handlers = {
 start : function (req, resp) {
  // ...
  },

 upload : function (req, resp) {
  // ...
  } 
};

export.handleRequest(name, req, resp) {
  if (handlers[name] !== undefined) {
    handlers[name](req,resp);
    return true;
  }
  // do special cases (if there are any)
  if (name === '') {
    handlers.start(req,resp);
    return true;
  }
  return false; // not found
}

/ , . , .

+4

All Articles