Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express4. What's the difference between app.locals, res.locals and req.app.locals?

I am so confused while using express 4. I use express-generator to generate my project. And there are app.js in root and index.js in router file. However, the tutorial on internet about express are using router directly in app.js. So when I want to set some variables in index.js(in router file), I use app.locals, but it doesn't work. But when I change to the other two, my ejs template works... I am very confused. Anybody can tell me the difference between them and how to use correctly, please?

<!-- language: index.js in router file -->

    var app = require('express');
    var router = express.Router();

    ....

router.get('/', function(req, res, next) {
    var _user = req.session.user;
    if (_user) {
      //does't work!!
      //app.locals.user=_user;
      //I am not sure about which usage is correct below
      //1.
      req.app.locals.user = _user;
      //2.
      // res.locals.user=_user;
    }
}

<!-- language: lang-ejs -->

    <% if (user) { %>
      <li><a class="navbar-link">Welcome <%= user.name %></a>
      </li>
      <span>&nbsp;|&nbsp;</span>
      <li><a href="/logout" class="navbar-link" id="logoutBtn">Logout</a>
      </li>
      <% } else { %>
        <li><a href="#" class="navbar-link" data-toggle="modal" data-target="#signinModal">登录</a>
        </li>
        <span>&nbsp;|&nbsp;</span>
        <li><a href="#" class="navbar-link" data-toggle="modal" data-target="#signupModal">注册</a>
        </li>
      <% } %>
like image 596
lwd931227 Avatar asked Jan 31 '16 06:01

lwd931227


1 Answers

From express documentation.

Here in short.

app.locals

The app.locals object is a JavaScript object, and its properties are local variables within the application.

This means you can declare a variable in your app.js with locals and access it within that script or pass it to the response object.

res.locals

With this you can set or send variables to client side html/view and it is only available in that view/html.

e.g.

app.get('/view', function(req, res) {
  res.locals.user = req.user;
});

Here the user variable is available in your html page requesting the view route.

req.app.locals

Locals are available in middleware via req.app.locals;

like image 81
RIYAJ KHAN Avatar answered Oct 27 '22 00:10

RIYAJ KHAN