简体   繁体   English

Express.js 4:如何访问app.locals。 <myvar> 在routes / index.js中?

[英]Express.js 4: How to access app.locals.<myvar> in routes/index.js?

I want access my own variable, app.locals.port , from app.js, inside my routes/index.js file. 我想从我的route / index.js文件中的app.js访问我自己的变量app.locals.port

app.js: app.js:

app.locals.port = 3001;
var index = require('./routes/index');
app.use('*', index); // use router in ./routers/index.js

routes/index.js: 路由/index.js:

var app = require('../app');

console.log('app.locals.port: ' + app.locals.port);

Output in my log when running npm start --> nodemon -e css,ejs,js,json,html,pug ./bin/www : 运行npm start时在我的日志中输出-> 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

My current workaround is to use a global: 我当前的解决方法是使用全局:

app.js app.js

global.port = 3001;

routes/index.js 路线/index.js

console.log('global.port: ' + global.port);

Thank you. 谢谢。

You need to pass the app object through to routes/index.js. 您需要将应用程序对象传递给route / index.js。

So in your app.js file you could have something like: 因此,在您的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)
})

and then in routes/index.js : 然后在route / 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
}

The app variable in routes/index.js will then be available within the scope of the module.exports function, which can then be passed to other functions within the file. 然后,routes / index.js中的app变量将在module.exports函数的范围内可用,然后可以将其传递到文件中的其他函数。

As you've also mentioned in the comments, the app object is attached to each request, so if you only need access to the app object within the scope of a route, you simplify your code. 正如您在注释中还提到的那样,每个请求都附加了app对象,因此,如果仅需要在路由范围内访问app对象,则可以简化代码。

app.js 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)
})

routes/index.js 路线/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM