javascript - Express.js 4: How to access app.locals.<myvar> in routes/index.js? -


i want access own variable, app.locals.port, app.js, inside routes/index.js file.

app.js:

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

routes/index.js:

var app = require('../app');  console.log('app.locals.port: ' + app.locals.port); 

output in log when running npm start --> nodemon -e css,ejs,js,json,html,pug ./bin/www:

[nodemon] 1.11.0 [nodemon] restart @ time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node ./bin/www` app.locals.port: undefined 

my current workaround use global:

app.js

global.port = 3001; 

routes/index.js

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

thank you.

you need pass app object through routes/index.js.

so in app.js file have like:

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 in routes/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 index.js!')     })      return router } 

the app variable in routes/index.js available within scope of module.exports function, can passed other functions within file.

as you've mentioned in comments, app object attached each request, if need access app object within scope of route, simplify code.

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

const express = require('express')  const router = express.router()   router.get('/', function(req, res) {     console.log(req.app.locals.port)     res.send('hello index.js!') })  module.exports = router 

Comments

Popular posts from this blog

javascript - Confirm a form & display message if form is valid with JQuery -

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -