【问题标题】:Node.js / Express - How to get variables defined in app.js in routes/index.js?Node.js / Express - 如何在路由/index.js 中获取 app.js 中定义的变量?
【发布时间】:2014-01-17 12:22:52
【问题描述】:

我是 Node.js 和 Express 的新手。

如何访问在“routes/index.js”中名为“pg”的“app.js”中创建的变量?

app.js

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var pg = require('pg');
var conString = "postgres://someuser:somepass@localhost/postgres"

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

路由/index.js

/*
 * GET home page.
 */

exports.index = function(req, res){

    var client = new pg.Client(conString);
    client.connect(function(err) {
      if(err) {
        return console.error('could not connect to postgres', err);
      }
      client.query('SELECT NOW() AS "theTime"', function(err, result) {
        if(err) {
          return console.error('error running query', err);
        }
        console.log(result.rows[0].theTime);
        //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
        client.end();
      });
    });

我在浏览器中收到错误:

Express 500 ReferenceError: pg is not defined

你们能给我一个线索吗?

最好的问候

【问题讨论】:

  • 您可能只想在您希望使用它的文件中重新要求 pg。Node 具有模块缓存,这意味着您必须竭尽全力强制它实际运行重新处理该文件,因此在另一个文件中再次require('pg') 并不昂贵。

标签: node.js express node-postgres


【解决方案1】:

在 Express 中将任何内容传递给路由处理程序(无论它们是否在不同文件中声明)的一种简单方法是使用 app.locals

// app.js
...
var app = express();
...
app.locals.someVar = someValue;
...

// somewhere else
module.exports.myhandler = function(req, res) {
  var someVar = req.app.locals.someVar;
  ...
};

【讨论】:

  • 感谢您的快速拍摄。
【解决方案2】:
// app.js
var routes = require('./routes/index')({ varname: thevar });
...
...

// /routes/index.js
module.exports = function(options) {
    var moduleVar = options.varname;

    return {
        someMethod: function (req, res) { var i = moduleVar + 2; // etc},
        anotherMethod: function (req, res) {}
    };
};

我在创建连接(或连接池)时执行此操作,并且只是希望我的模块能够访问数据库而无需创建另一个连接。当然,这一切都取决于您的项目,我的一个命中跟踪模块使用它自己的连接,所以我将数据库信息传递给它,然后它从那里做它自己的事情。这允许我有多个应用程序使用此跟踪器模块,同时每个应用程序都连接到自己的数据库。

【讨论】:

  • 当我这样做时“var routes = require('./routes')({ pg: pg, conString: conString});”我收到错误,TypeError: object is not a function
  • 您是否修改了您的路线模块?如果它没有包含在exports = function(options)中,它将无法工作。
【解决方案3】:

您可以在不使用 var 关键字的情况下定义变量以使变量成为全局变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2017-12-21
    • 2012-04-03
    相关资源
    最近更新 更多