P
P
pomeo2013-04-19 17:25:50
JavaScript
pomeo, 2013-04-19 17:25:50

express.js and variables

There is for example a basic express.js skeleton

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// для примера пусть будет переменная, но может быть и функция. Пример сильно упрощённый.
var a = 1;

app.get('/', routes.index);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

routes/index.js internals
exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};

The question is, how can I var a = 1;throw inside routes.index? Without creating a aglobal and without writing all the code in app.js.

Google didn’t really help, examples from visionmedia themselves show what they do appglobal line 11 github.com/visionmedia/screenshot-app/blob/master/app.js
then start app.dbin a specific example and then it is used by routes, line 7 github.com /visionmedia/screenshot-app/blob/master/routes/palette.js
Interested in other ways, if they are of course.
Everything is fine with templates, there areapp.locals

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2013-04-19
@pomeo

For example, like this:

app.use(function(req, res, next) {
  req.app = app;
  next();
});

Accordingly, req.app.locals can be accessed in the route.

N
Nook Scheel, 2014-01-21
@inook

Correct use like this:

app.set('foo', 'bar');
app.use(function (req, res, next) {
  res.locals.foo = 'BAR'
});
app.get('/', function (req, res, next) {
  console.log(req.app.get('foo')); // bar
  console.log(res.app.get('foo')); // bar
  // res.locals передаются во view engine вместе c app.locals
  console.log(res.locals.foo); // BAR
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question