Is it possible to call Express Router directly from code with a “fake” request?

后端 未结 3 1440
南笙
南笙 2020-12-09 04:16

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?

3条回答
  •  醉梦人生
    2020-12-09 04:38

    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.

提交回复
热议问题