【问题标题】:How to use app.js variables in all routes file?如何在所有路由文件中使用 app.js 变量?
【发布时间】:2017-12-21 15:16:57
【问题描述】:

如何在 routes/index.js 文件中使用clients 变量。

这是我的代码,

app.js

clients = new cassandra.Client({ contactPoints:[config.contactPoints], keyspace: config.keyspace,authProvider: new cassandra.auth.PlainTextAuthProvider(config.userName, config.password)});

【问题讨论】:

  • 这是一个 Express 应用程序吗?
  • 是的,这是快速应用程序@ImClarky

标签: node.js cassandra


【解决方案1】:

您可以在 index.js 中定义一个方法,将其导出并将客户端作为参数传递给创建的方法。

在 index.js 中

var clients;

exports.assignVal = function(clients){
    this.clients = clients;
};

在 app.js 中

routes = require('./index');
routes.assignVal(clients);

【讨论】:

  • 谢谢我试过你的代码,但它的返回错误如 TypeError: routes.assignVal is not a function
【解决方案2】:

如果您希望这个变量分别针对每个请求,您可以使用res.locals,在其他情况下您可以使用app.locals

【讨论】:

  • 感谢您,但如果您提供直接解决方案而不是文档,它将更有帮助,因为我是节点 js 的新手。
【解决方案3】:

您可以稍微更改路由器文件以传入参数。像这样:

var express = require('express')
var router = express.Router()

module.exports = function(your variable) {
  // router.get(...) etc.

  return router
}

然后在app.js,当你require你的路由器时:

var index = require('./routes/index')(your variable)

显然,请确保在需要您的路由器之前定义您的变量。

【讨论】:

  • 谢谢我试过你的代码,但它的返回错误如 TypeError: Cannot read property 'apply' of undefined in app.js
猜你喜欢
  • 2012-04-03
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多