Bardelman Bardelman - 4 days ago 6
Jade Question

Express.js : variable stored in `res.locals` isn't defined in the view

In an express application, i'm using an express router declared in the

app.js
as:

var adminRouter = require('./admin');
app.use("/admin", adminRouter);


so it references the
admin.js
file in which i defined this specific route :

router.route('/rooms/edit/:id')
.all(function(req, res, next) {
var roomid = req.params.id;
var room = _.find(rooms, r => r.id == roomid);
if (!room) {
res.sendStatus(404);
return;
}
res.locals.room = room;
next();
}).get(function(req, res) {

res.render('edit', { room: room });
}).post(function(req, res) {

res.locals.room.name = req.body.name;
res.redirect('./');
});


but in the view for editing the room name (accessed by the .get method in the route above) i get this error saying that the
room
variable i stored in
res.locals
isn't defined :

ReferenceError: room is not defined


here is the whole
app.js


var express = require('express');
var app = express();
var bodyParser = require('body-parser');


app.set("views", "./views");
app.set("view engine", "jade");

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));


app.use(function(req, res, next){
console.log('incomming req : ' + req.url);
next();
});

app.get('/', function(req, res){
res.render('index', {title:'Home'});
});

var adminRouter = require('./admin');
app.use("/admin", adminRouter);

app.listen(3000, function(){
console.log('app running on port 3000');
});


and this is the edit.jade view too :

extends layout
block content
h1 Edit chatroom!!
form(method="POST")
fieldset.form-group
label(for="name") Name:
input.form-control(name="name", type="text", placeholder="Enter a name" value="#{room.name}")
small.text-muted Give your chatroom a meaningful name for people to refer to it.
button.btn.btn-primary(type="submit") Save chatroom
a.btn.btn-default(href="/admin/rooms") Cancel

Answer

i get this error saying that the room variable i stored in res.locals isn't defined :

ReferenceError: room is not defined

That's not what the error says: it says that a variable called room isn't defined. It should have also pointed you to the line of code where the error happens, which is here:

res.render('edit', { room: room });

Where, in fact, room is undefined.

Comments