Tangential to this question, I would like to find out if there is a way of triggering the Express Router without actually going through HTTP?
By going to the source of Express, I was able to find out that there is indeed an API that is just as simple as I wished for. It is documented in the tests for express.Router.
/**
* @param {express.Router} router
*/
function dispatchToRouter(router, url, callback) {
var request = {
url : url,
method : 'GET'
};
// stub a Response object with a (relevant) subset of the needed
// methods, such as .json(), .status(), .send(), .end(), ...
var response = {
json : function(results) {
callback(results);
}
};
router.handle(request, response, function(err) {
console.log('These errors happened during processing: ', err);
});
}
But ... the downside is, exactly the reason why it is undocumented in the first place: it is a private function of Router.prototype:
/**
* Dispatch a req, res into the router.
* @private
*/
proto.handle = function handle(req, res, out) {
var self = this;
...
}
So relying on this code is not the safest thing in the world.