简体   繁体   English

如何在所有路由文件中使用app.js变量?

[英]How to use app.js variables in all routes file?

How to use clients variable in routes/index.js files. 如何在route / index.js文件中使用clients变量。

here is my code, 这是我的代码,

app.js app.js

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

You can define a method in index.js, export it and pass clients as a parameter to the created method. 您可以在index.js中定义一个方法,将其导出并将客户端作为参数传递给创建的方法。

In index.js 在index.js中

var clients;

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

In app.js 在app.js中

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

如果希望将此变量分别用于每个请求,则可以使用res.locals否则可以使用app.locals。

You can alter your router files slightly to pass in a parameter. 您可以稍微更改路由器文件以传递参数。 Like so: 像这样:

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

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

  return router
}

Then in app.js , when you require your routers: 然后在app.js ,当您require路由器时:

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

Obviously, make sure that your variable is defined before requiring your routers. 显然,在需要路由器之前,请确保已定义变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将app.js中的公共变量渲染到express中的所有路径 - how to render common variables from app.js to all routes in express Node.js / Express - 如何在routes / index.js中的app.js中定义变量? - Node.js / Express - How to get variables defined in app.js in routes/index.js? 在路由中访问app.js变量但没有全局表达 - Access app.js variables in routes but without global express 如何将数据从一个 app.js 文件发送到 Routes 中的 index.ejs 文件 - how do I send data from one app.js file to index.ejs file in Routes 我如何使用外部路由.js所以我不必在app.js中定义我的路由? - How do I use external routes.js so I don't have to define my routes in app.js? app.js中定义的变量是否可以通过Express和node js中的路由功能访问? - Are the variables defined in app.js accessible to the functions in routes, in Express and node js? 节点快递路线和app.js - Node express routes and app.js app.js 中的全局变量可在路由中访问? - Global Variable in app.js accessible in routes? 如何使用在 _app.js (Next.js) 中声明的全局 css 文件中的 css class - How to use css class from global css file declared inside _app.js (Next.js) 为什么需要require('/ routes')(app); 不等于在一个app.js文件中具有相同的代码? - Why is require('/routes')(app); not equivalent to having the same code in one app.js file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM