2017-04-07 46 views
0

我想從我的routes/index.js文件中的app.js訪問我自己的變量app.locals.portExpress.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); 

謝謝。

回答

1

您需要將應用程序對象傳遞給routes/index.js。

所以在你app.js文件,你可以有這樣的:

const express = require('express') 

const app = express() 
app.locals.port = 3001 

const index = require('./routes/index')(app) 

app.use('*', index) 

app.listen(app.locals.port, function() { 
    console.log('Server listening on ' + app.locals.port) 
}) 

,然後在路線/ index.js

const express = require('express') 

module.exports = function(app) { 

    const router = express.Router() 

    router.get('/', function(req, res) { 
     console.log(app.locals.port) 
     res.send('Hello from index.js!') 
    }) 

    return router 
} 

在路由app變量/ index.js將在module.exports函數的範圍內可用,然後可以將其傳遞給文件中的其他函數。

正如您在評論中提到的,應用程序對象附加到每個請求,所以如果您只需要訪問路徑範圍內的應用程序對象,就可以簡化代碼。

app.js

const express = require('express') 

const app = express() 
app.locals.port = 3001 

const index = require('./routes/index') 

app.use('*', index) 

app.listen(app.locals.port, function() { 
    console.log('Server listening on ' + app.locals.port) 
}) 

路線/ index.js

const express = require('express') 

const router = express.Router() 

router.get('/', function(req, res) { 
    console.log(req.app.locals.port) 
    res.send('Hello from index.js!') 
}) 

module.exports = router 
+0

我想在我自己的應用程序,得到這個'/用戶/佩德羅的/ 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));' –

+0

我重新嘗試了一些我以爲我會已經完成 - 通過請求/路由處理程序中的'req'對象訪問'app' - 這是我正在尋找的一部分。理想情況下,如果願意,我希望'app' var/object在這些處理程序之外可用 - 在'文件範圍'處。(請求,資源,下一個)console.log(req.app.get('view engine')); console.log(req.app.locals.port );' –

+0

@PeterSmith對不起,我的答案已經更新了,所以它與你提供的代碼更接近,希望有幫助。 – dan