get user agent from inside jade

后端 未结 2 714
执笔经年
执笔经年 2021-01-12 02:07

I am trying to port a script I wrote for groovy over to jade, and have run into a stumbling block

I need to access the user-agent from inside a jade file. Here is wh

2条回答
  •  天涯浪人
    2021-01-12 02:39

    Just write your own tiny middleware

    app.use(function(req, res, next) {
      res.locals.ua = req.get('User-Agent');
      next();
    });
    

    Put this before your app.router

    app.configure(function(){
      app.set('port', process.env.PORT || 3000);
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.use(express.favicon());
      app.use(express.logger('dev'));
      app.use(express.bodyParser());
      app.use(express.methodOverride());
    
      // here
      app.use(function(req, res, next) {
        res.locals.ua = req.get('User-Agent');
        next();
      });
    
      app.use(app.router);
      app.use(express.static(path.join(__dirname, 'public')));
    });
    

    Then you can use the ua variable in any jade template (for example index.jade)

    extends layout
    
    block content
      h1= title
      p Welcome to #{title}
      p=ua
    

提交回复
热议问题