0
我想從我的routes/index.js文件中的app.js訪問我自己的變量app.locals.port
。Express.js 4:如何訪問app.locals。 <myvar> in routes/index.js?
app.js:
app.locals.port = 3001;
var index = require('./routes/index');
app.use('*', index); // use router in ./routers/index.js
路線/ index.js:運行npm start
當
var app = require('../app');
console.log('app.locals.port: ' + app.locals.port);
輸出在我的日誌 - >nodemon -e css,ejs,js,json,html,pug ./bin/www
:
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
app.locals.port: undefined
我目前的解決辦法是使用一個全球性的:
app.js
global.port = 3001;
路線/ index.js
console.log('global.port: ' + global.port);
謝謝。
我想在我自己的應用程序,得到這個'/用戶/佩德羅的/ dev/antsirs/node_modules/express/lib/router/index.js:635 返回fn.apply(this,arguments);',然後從一個新生成的cli express應用程序中,[nodemon]起始節點./bin/www /Users /佩德羅的/ dev/tmp目錄/ testexpresscli/node_m odules/express/lib/router/index.js:458 扔新TypeError('Router.use()需要中間件功能,但得到'+ gettype(fn));' –
我重新嘗試了一些我以爲我會已經完成 - 通過請求/路由處理程序中的'req'對象訪問'app' - 這是我正在尋找的一部分。理想情況下,如果願意,我希望'app' var/object在這些處理程序之外可用 - 在'文件範圍'處。(請求,資源,下一個)console.log(req.app.get('view engine')); console.log(req.app.locals.port );' –
@PeterSmith對不起,我的答案已經更新了,所以它與你提供的代碼更接近,希望有幫助。 – dan