2
這是我在app.js配置:訪問app.js變量的路線,但沒有全球快遞
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, Server = mongo.Server
, Db = mongo.Db;
, mongo = require('mongodb');
, BSON = mongo.BSONPure;
var app = express();
var server = new Server('localhost', 27017, {auto_reconnect: true, });
var db = new Db('tasksdb', server); //i need to remove this "var" to access db in routes
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'tasksdb' database");
db.collection('tasks', {safe:true}, function(err, collection) {
if (err) {
console.log("The 'tasks' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
app.get('/', routes.index);
app.get('/tasks', routes.getAllTasks);
在路由/ index.js我有:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
exports.getAllTasks = function (req, res) {
db.collection('tasks', function (err, collection){ //this "db" is not accessible unless i remove "var" from db in app.js
collection.find().toArray(function (err, items) {
res.send(items);
})
})
};
這是當然的不工作,除非我從app.js中的「db」中刪除「var」,然後它變成全局的,我可以在路由中訪問它,但我不想在我的代碼中使用全局變量,也不想將控制器操作移動到應用程序.js文件。如何解決它?
它實際上只是它的全局文件,當它與var - 當我刪除它 - 成爲全球和所有文件的可用性。感謝您的幫助 - 它運作良好:) – Kriss 2013-02-23 09:59:54
如何從routes/index.js獲取anyObj? //app.js const的應用程式=快遞() const的路由=要求( './路由 ') app.use('/',路由) app.set( 'anyObj',{} ) //路由/ index.js 常量表達=要求( '表示') const的路由器= express.Router() const的用戶需要=(」 ./用戶 ') router.use('/ api/users',用戶) – aung 2017-07-19 00:55:21