gpt4 book ai didi

javascript - 创建一个 javascript 对象并绑定(bind)它

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:07 24 4
gpt4 key购买 nike

我正在尝试构建我的第一个 Node 应用程序。我的 app.js 文件如下所示。我想通过执行“app = require('app')”从另一个模块访问它。然后我想访问 app.app、app.dbConn 和 app.models

问题是,当我需要此模块时,结果对象上不存在 app.models。

var express = require('express');
var path = require('path');
var orm = require('orm');

var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');

module.exports = new function(){
this.app = express();

// middlewares must be added in order - start with the basics
environment(this.app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }

// add models to the request early in the middleware chain
this.dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
this.models = db.init(this.dbConn);
this.app.use(function(req,res,next){
req.models = this.models;
next();
});

passport = auth.init(this.models);
authRouter = auth.router(passport)

this.app.use('/users', authRouter);
this.app.use(mainRouter);
}
}.bind(this));
this.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
}

实现我想要的唯一方法是使用一个带有回调的函数,最后我这样重写了我的代码:

var express = require('express');
var path = require('path');
var orm = require('orm');

var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');

var app;

module.exports = function(cb){
app = express();

// middlewares must be added in order - start with the basics
environment(app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }

// add models to the request early in the middleware chain
dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
models = db.init(dbConn);
app.use(function(req,res,next){
req.models = models;
next();
});

passport = auth.init(this.models);
authRouter = auth.router(passport)

app.use('/users', authRouter);
app.use(mainRouter);

cb({
dbConn: dbConn,
app: app,
models: models
});
}
});
}

if (!process.env.TESTING) {
module.exports(function(server){
server.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
});
}

最佳答案

app.models 仅在数据库连接完成后定义:您不能在需要模块后立即使用它。您应该提供一个入口点,该入口点接受连接准备好后要调用的函数,并在 orm.connect 回调中调用该函数。

即使是“服务器已启动”消息也有点误导,因为它在服务器实际上可以执行任何操作之前显示,因为传递给 orm.connect 的函数尚未被调用。

关于javascript - 创建一个 javascript 对象并绑定(bind)它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706472/

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