node.js Express:访问路由中的 app.set() 设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14822584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:08:39  来源:igfitidea点击:

Express: accessing app.set() settings in routes

node.jsexpress

提问by Scott

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.jsfile:

在 Express 中,我相信可以通过在我的主app.js文件中执行类似于以下内容的操作来创建全局应用程序设置:

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);
...

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):

现在./routes/login.js,我想访问app.settings.ssoHostname,但是如果我尝试运行类似于以下内容的任何内容(根据: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));
  }
};
...

it does not recognize app:

它不承认app

ReferenceError: app is not defined

My questions are:

我的问题是:

  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?
  1. app.set()用于全局设置的方法是经常重复使用的“正确”方法吗,如果是的话......
  2. 如何在路由中访问这些设置?
  3. 如果不app.set()用于经常使用的全局设置,我将如何在路由中设置和获取自定义设置?

采纳答案by pifantastic

At the end of your app.jsfile:

在您的app.js文件末尾:

module.exports = app;

And then in routes/login.js:

然后在routes/login.js

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

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

现在您可以访问实际app对象并且不会获得ReferenceError.

回答by Darius Kucinskas

Use req.app.get('ssoHostname')

req.app.get('ssoHostname')