我正在尝试在 kraken.js 应用程序中的 app
对象上关联一个方法或属性,如下所示:
controllers/index.js
'use strict';
var IndexModel = require('../models/index');
module.exports = function (app) {
var model = new IndexModel();
app.get('/', function (req, res) {
console.log(app.adventurer);
/* Console should be showing "Bilbo Bagins", but I'm getting 'undefined'.
* See the next source file. */
res.render('index', model);
});
};
/index.js
var kraken = require('kraken-js'),
app = {
adventurer: 'Bilbo Bagins'
};
app.configure = function configure(nconf, next) {
// Async method run on startup.
next(null);
};
app.requestStart = function requestStart(server) {
// Run before most express middleware has been registered.
};
app.requestBeforeRoute = function requestBeforeRoute(server) {
// Run before any routes have been added.
};
app.requestAfterRoute = function requestAfterRoute(server) {
// Run after all routes have been added.
};
if (require.main === module) {
kraken.create(app).listen(function (err) {
if (err) {
console.error(err.stack);
}
});
}
module.exports = app;
此外,我尝试在 /config/app.json
上发布该属性
有什么想法吗?
最佳答案
只需将以下 key 添加到 .config/app.json 或创建一个新的 .config/app-development.json:
"adventurer": "bilbo"
app.json 将如下所示:
{
//blah
//blah
"adventurer": "bilbo"
}
然后在 ./index.js 中进行配置:
app.configure = function configure(nconf, next) {
// Async method run on startup.
next(null);
console.log('my traveler is: ', nconf.get('adventurer'));
};
为了回应您的评论,如果您想从 ./controllers/index.js 获取应用程序配置,则需要 nconf lib 并使用 nconf.get,如下所示:
'use strict';
var nconf = require('nconf');
var IndexModel = require('../models/index');
module.exports = function (app) {
var model = new IndexModel();
//or attach it directly to the app object like so
app.set('adventurer', nconf.get('adventurer'));
console.log('adventurer directly set on app object', app.get('adventurer'));
console.log('controller with app adventurer:', nconf.get('adventurer'));
app.get('/', function (req, res) {
res.render('index', model);
});
};
使用 npm start 启动它并观察控制台。和平!
关于javascript - 在 Controller 内部的应用程序对象上嵌入属性或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22461819/