Node.js 如何在所有路由文件中使用app.js变量?
如何在routes/index.js文件中使用Node.js 如何在所有路由文件中使用app.js变量?,node.js,cassandra,Node.js,Cassandra,如何在routes/index.js文件中使用客户端变量 这是我的密码 app.js clients = new cassandra.Client({ contactPoints:[config.contactPoints], keyspace: config.keyspace,authProvider: new cassandra.auth.PlainTextAuthProvider(config.userName, config.password)}); 您可以在index.js中定义一个
客户端
变量
这是我的密码
app.js
clients = new cassandra.Client({ contactPoints:[config.contactPoints], keyspace: config.keyspace,authProvider: new cassandra.auth.PlainTextAuthProvider(config.userName, config.password)});
您可以在index.js中定义一个方法,导出它并将客户端作为参数传递给创建的方法 在index.js中
var clients;
exports.assignVal = function(clients){
this.clients = clients;
};
在app.js中
routes = require('./index');
routes.assignVal(clients);
如果您希望将此变量的作用域分别用于每个请求,您可以使用,在其他情况下,您可以使用,您可以稍微更改路由器文件以传入参数。像这样:
var express = require('express')
var router = express.Router()
module.exports = function(your variable) {
// router.get(...) etc.
return router
}
然后在app.js
中,当您需要
路由器时:
var index = require('./routes/index')(your variable)
显然,,请确保在要求路由器之前定义了变量。谢谢,我尝试了您的代码,但其返回错误如TypeError:routes.assignVal不是一个函数。这是一个Express应用程序吗?是的,这是Express application@Imclarky谢谢,但如果您提供直接解决方案而不是文档,则会更有帮助,因为我是在node js中新增。谢谢,我尝试了您的代码,但返回的错误类似于TypeError:无法读取app.js中未定义的属性“apply”