gpt4 book ai didi

node.js - 在路由中访问 app.js 变量但没有全局 express

转载 作者:搜寻专家 更新时间:2023-11-01 00:11:17 24 4
gpt4 key购买 nike

这是我在 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);

在 routes/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”,然后它变成全局的,我可以在路由中访问它,但我不想在我的代码中使用全局变量,也不想想要将 Controller 操作移动到 app.js 文件。如何解决???

最佳答案

我不确定我是否理解。 db 是否是全局的,有或没有 var(对我来说它看起来像一个全局范围)?此外,你为什么不希望它是全局性的?这是使用全局变量的一个很好的例子。

但它不会在文件之间共享。您必须将其添加到导出中。试试这个:

app.js

exports.db = db;

routes/index.js

var db = require("app").db;

另一种方法是将 db 添加到每个处理程序,如下所示:

app.js

app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', routes.index);
app.get('/tasks', routes.getAllTasks);

那么它应该在任何路由中都可用 req.db

关于node.js - 在路由中访问 app.js 变量但没有全局 express ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15039045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com