Node.js / Express.js - How to override/intercept res.render function?

后端 未结 4 1960
囚心锁ツ
囚心锁ツ 2020-12-05 07:09

I\'m building a Node.js app with Connect/Express.js and I want to intercept the res.render(view, option) function to run some code before forwarding it on to the original r

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 08:06

    I recently found myself needing to do the same thing, to provide a configuration-specific Google Analytics property id and cookie domain to each of my templates.

    There are a number of great solutions here.

    I chose to go with something very close to the solution proposed by Lex, but ran into problems where calls to res.render() did not already include existing options. For instance, the following code was causing an exception in the call to extend(), because options was undefined:

    return res.render('admin/refreshes');
    

    I added the following, which accounts for the various combinations of arguments that are possible, including the callback. A similar approach can be used with the solutions proposed by others.

    app.use(function(req, res, next) {
      var _render = res.render;
      res.render = function(view, options, callback) {
        if (typeof options === 'function') {
          callback = options;
          options = {};
        } else if (!options) {
          options = {};
        }
        extend(options, {
          gaPropertyID: config.googleAnalytics.propertyID,
          gaCookieDomain: config.googleAnalytics.cookieDomain
        });
        _render.call(this, view, options, callback);
      }
      next();
    });
    

    edit: Turns out that while this all might be handy when I need to actually run some code, there's a tremendously simpler way to accomplish what I was trying to do. I looked again at the source and docs for Express, and it turns out that the app.locals are used to render every template. So in my case, I ultimately replaced all of the middleware code above with the following assignments:

    app.locals.gaPropertyID = config.googleAnalytics.propertyID;
    app.locals.gaCookieDomain = config.googleAnalytics.cookieDomain;
    

提交回复
热议问题