[英]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.