Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

res.locals returned undefined

I'm trying to set some response-specific variables, and I'm getting undefined for res.locals when I log it from within my middleware, but it returns the function just fine if I log it from within a route function.

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(function (res, req, next) {
  console.log("res.locals from app.use middleware: ", res.locals);
  // res.locals.boom = 'nice';
  // res.locals.zoom = 'yeah!';
  next();
});
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

Any ideas?

like image 738
Costa Michailidis Avatar asked Dec 26 '13 22:12

Costa Michailidis


People also ask

What does res locals mean?

The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.

What is locals in ejs?

Locals represent server-side data that is accessible to your view—locals are not actually included in the compiled HTML unless you explicitly reference them using special syntax provided by your view engine. <div>Logged in as <a><%= user.fullName %></a>.</

What is locals user?

In Windows, a local user is one whose username and encrypted password are stored on the computer itself.


2 Answers

You have your request & response objects backwards. Obviously if you know the difference in your code, naming doesn't matter, but best to keep things named correctly.

app.use( function (request, response, next) {
    // stuff
});

I can't recall off the top of my head, but I believe you want:

request.app.locals;

using my example above. Again, not 100% sure. You can always console out the request object to check.

like image 143
Chris Avatar answered Oct 03 '22 15:10

Chris


The app.locals object is a JavaScript Function, which when invoked with an object will merge properties into itself, providing a simple way to expose existing objects as local variables.

app.locals({
  title: 'My App',
  phone: '1-250-858-9990',
  email: '[email protected]'
});

app.locals.title
// => 'My App'

app.locals.email
// => '[email protected]'
like image 41
softvar Avatar answered Oct 03 '22 15:10

softvar