Hi I have some newbie questions about the use of res (Express response object) and res.locals in Express.
While studying nodejs in one of the code examples There is a middleware (messages.js), a server (app.js) and the template (messages.ejs). Looking into the sample code for the template. It appears that although messages and removeMessages() is assigned to res.locals. You can access them using messages or removeMessages() without prefixing the call with locals. I wish to know the following:
- Are they pointing to the same objects?
- If they are the same does it matter if I assign to res direct instead of res.locals?
Sample Code
messages.js
var express = require('express');
var res = express.response;
res.message = function (msg, type) {
type = type || 'info'
var sess = this.req.session;
sess.messages = sess.messages || [];
sess.messages.push({
type: type,
string: msg
});
};
res.error = function (msg) {
return this.message(msg, 'error');
};
module.exports = function (req, res, next) {
res.locals.messages = req.session.messages || [];
res.locals.removeMessages = function () {
req.session.messages = [];
};
next();
};
app.js(partial code)
var express = require('express');
var messages = require('./lib/messages');
var app = express();
app.use(messages);
messages.ejs
<% if(locals.messages) { %>
<% messages.forEach(function (message) { % %>
<p class = '<%= message.type %>' > <%= message.string %> < /p>
<% }) %>
<% removeMessages(); %>
<% } %>