简体   繁体   中英

app.get returned undefined in Node/Express

I'm using express in my app.js I set something like this

var express = require('express');
var app = express();
app.set('myVar', 'hello');

then in my controller I want to get the value. I do

var express = require('express');
var app = express();
console.log(app.get('myVar')) // undefineded 

Any idea why?

Your controller creates a new, fresh instance of Express. If you want to be able to share variables, you need to pass the instance from app.js to your controller:

// app.js
var express = require('express');
var app = express();
app.set('myVar', 'hello');
require('./controller')(app);

// controller.js
module.exports = function(app) {
  console.log(app.get('myVar'));
};

EDIT : judging by the comments, the issue isn't so much passing app around, but moving parts of the application to separate modules. A common setup to enable that would look like this:

// app.js
var express = require('express');
var app = express();
app.set('myVar', 'hello');

app.use('/api', require('./controller/auth'));

// controller/auth.js
var express = require('express');
var router  = express.Router();

router.get('/', function(req, res) {
  console.log(req.app.get('myVar'));
  return res.send('hello world');
});

module.exports = router;

In your example you are instantiating a second app that you then try to get the value from. You need to get from the exact same object:

var express = require('express');
var app = express();
app.set('foo', 'bar');
app.get('foo');

If you are new to express, you can use the cli generator to scaffold out an application that shows you a sane pattern how to use the same express instance throughout your whole application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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