Express:访问路由中的app.set()设置 [英] Express: accessing app.set() settings in routes

查看:464
本文介绍了Express:访问路由中的app.set()设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Express中,我被认为可以通过在主要的 app.js 文件中执行类似以下操作来创建全局应用设置:

In Express, I'm led to believe that global app settings can be created by doing something similar to the following in my main app.js file:

var express = require('express'),
    ...
    login = require('./routes/login');

var app = express();

app.configure(function(){
  ...
  app.set('ssoHostname', 'login.hostname.com');
  ...
});
...
app.get('/login', login.login);
...

现在在 ./ routes / login中。 js ,我想访问 app.settings.ssoHostname ,但是如果我尝试运行类似的内容(如下所示:如何访问使用app.set()在express js中设置的变量):

now in ./routes/login.js, I'd like to access app.settings.ssoHostname, but if I attempt to run anything similar to (as per: How to access variables set using app.set() in express js):

...
exports.login = function(req, res) {
  var currentURL = 'http://' + req.header('host') + req.url;
  if (!req.cookies.authCookie || !User.isValidKey(req.cookies.authCookie)) {
    res.redirect(app.settings.ssoHostname + '/Login?returnURL=' + encodeURIComponent(currentURL));
  }
};
...

它无法识别应用程序

ReferenceError: app is not defined

我的问题是:


  1. 使用 app.set()为全局设置,将经常重复使用正确的方式,如果是这样...

  2. 如何在路由中访问这些设置?

  3. 如果不经常使用全局设置的 app.set()我会在路线中设置和获取自定义设置吗?

  1. Is the approach I took of using app.set() for global settings that will be re-used often the "proper" way to do it and if so...
  2. How do I access these settings in routes?
  3. If not using app.set() for global settings to be used often, how would I set and get custom settings in routes?


推荐答案

在$ code> app.js file:

At the end of your app.js file:

module.exports = app;

然后在 routes / login.js

var app = require('../app');

现在您可以访问实际的应用程序对象并且不会得到一个 ReferenceError

Now you have access to the actual app object and won't get a ReferenceError.

这篇关于Express:访问路由中的app.set()设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆