Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  142] [ 2]  / answers: 1 / hits: 22217  / 8 Years ago, sun, january 31, 2016, 12:00:00

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>
<% } %>

More From » node.js

 Answers
71

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



    app.locals.title
    // => 'My App'
    app.locals.email
    // => '[email protected]'


    Once set, the value of app.locals properties persist throughout the life of the application


  • In contrast with res.locals properties that are valid only for the lifetime of the request. When you handle the route where you have a res object, you won't have an app object there and vice-versa for app.locals.


  • You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data. Locals are available in middleware via req.app.locals (see req.app)



    app.locals.title = 'My App';
    app.locals.strftime = require('strftime');
    app.locals.email = '[email protected]';



One picture from Node.js In Action book as below, describe the difference of app.local and res.local



enter


[#63498] Thursday, January 28, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;