Cannot read property 'userName' of undefined, when trying to render a jade template












0















The strangest thing. I'm passing a value to a Jade 'variable' and the template reads the variable, as you can see its printed to the console (see 'this is1...this is2 etc') and rendered on the screen. However, the page seems to be getting rendered a second time, at which point the template has lost the value of the variable -> see 'this is1' on the second occurance.



I cant understand why the page is rendering twice. Also, I say its strange as the page appears to renders as normal, it's only when I check the log I can see errors and when I then try to make a request based on one of the variables object IDs it is clear that the template thinks the values of (currentUser) the varables are undefined, Any thoughts? I've been pulling y hair out about this. Thanks:



ROUTE.js:



router.get('/setuser/:id',ctrlPages.setUser);


CONTROLLER.js:



var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports.setUser = (req, res) => {
console.log('req param id', req.params.id);
User.find({_id: ObjectId(req.params.id)}, { new: true }, (err, u
userId) => {
console.log('userid',userId);
if (userId === null) {
console.log('error');
res.redirect('/');
}
else{
console.log('user set');
//currentUser = userId;
res.redirect('/');
}
});
};


TEMPLATE:



extends layout
include _includes/sharedHTMLfunctions
block content
.row.page-header
.col-lg-8
.row
.col-xs-12.col-sm-6
.panel.panel-primary
.panel-heading
h2.panel-title Admin page
- console.log('this is3',currentUser)
.panel-body
.text-center
.jumbotron
h4 This page is for managing users
h4 You will be able to create, delete and change
h4 the current system user. As well as add content.
h4 This will be entirely for black box testing and
h4 will not be acessible once the site is live.

h3 current user:
h2 #{currentUser.userName}
h2 Current users in database:
h3 this data is being supplied in real-time by the model

each user in userList
span.h4 Username:
span.h2= user.userName
- console.log('this is4',user)
p(style='text-align:right')
span.h4 Rating:
span.h2= user.rating
a(href="/setuser/#{user._id}")
button(type="button") set as user



.col-xs-12.col-md-6

h1 Add users
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="userName") user name
.col-xs-12.col-sm-8
input#name.form-control(name="userName")
.form-group
label.col-xs-10.col-sm-2.control-label(for="rating") rating
.col-xs-12.col-sm-2
select#rating.form-control.input-sm(name="rating")
option 10
option 9
option 8
option 7
option 6
option 5
option 4
option 3
option 2
option 1
button.btn.btn-default.pull-right(href="") Add user

h1 Add forum posts to current user
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="topic") post
.col-xs-12.col-sm-8
input#name.form-control(name="topic")


button.btn.btn-default.pull-right(href="") Add post


LAYOUT.jade



doctype html
html
head
meta(name='viewport', content='width=device-width, inital-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/bootstrap.css')
link(rel='stylesheet', href='/bootstrap/css/style.css')
link(rel='stylesheet', href='/bootstrap/css/forum.css')


body
navbar.navbar-defauly.navbar-fixed-top
.container
.navbar-header
a.navbar-brand(href="/home") Create Together
button.navbar-toggle(type="button", data-toggle="collapse", data-target="#navbar-main")
span.icon-bar
span.icon-bar
span.icon-bar
#navbar-main.navbar-collapse.collapse
ul.nav.navbar-nav.navbar-right
li
a(href='/unitplans') Unit planners
li
a(href='/forum') Forum
li
a(href='/helpme') Help me
li
a.selected(href='/') (Admin)
.col-lg-3
.panel.panel-primary
.panel-heading
h2.panel-title User information

.panel-body
.text-center
img(src='/uploads/avatar.jpg', width='200',height=-'300')

span.h4 Username
center
- console.log('this is1',currentUser)
span.h2= currentUser.userName

h4 Users who recently liked your work
center
li.span.h5 mathsGeek82
li.span.h5 algIsBest76
h4 Other site related information
h4 Rating
center
- console.log('this is2',currentUser)
+ratingText(currentUser.rating)
.container
block content
footer
.row
.col-xs-12
small footer

script(src='/javascripts/jquery-3.3.1.js')
script(src='/bootstrap/js/bootstrap.min.js')


CONSOLE log



adminFire
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is3 { userName: 'no user selected', rating: '10' }
this is4 { _id: 5bee3c67194ff91a857ba7ed,
userName: 'me',
rating: 5,
__v: 0 }
this is4 { _id: 5bee3e3953ae361b0f62d2a4,
userName: 'stev',
rating: 4,
__v: 0 }
this is4 { _id: 5bee3e91067d181b2fba359a,
userName: 'bollox',
rating: 8,
__v: 0 }
this is4 { _id: 5bee3eb0067d181b2fba359b,
userName: 'nick',
rating: 10,
__v: 0 }
GET / 200 938.186 ms - 4563
GET /bootstrap/css/bootstrap.css 304 15.842 ms - -
GET /bootstrap/css/style.css 304 10.458 ms - -
GET /bootstrap/css/forum.css 304 2.209 ms - -
GET /uploads/avatar.jpg 304 1.848 ms - -
this is1 undefined
GET /javascripts/jquery-3.3.1.js 404 146.950 ms - 3749
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:43
41| center
42| - console.log('this is1',currentUser)
> 43| span.h2 #{currentUser.userName}
44|
45| h4 Users who recently liked your work
46| center


EDIT:
Thanks Graham, however it didnt help. I added the return statement:



Here is my res.render code:



module.exports.admin = (req, res) => {
// user find by id then set to active user?
User.find((err, userList) => {
console.log('adminFire');
if (!err) {
console.log('return adb4');
res.render('locations-admin', {
title: 'Create Together',
userList: userList,
currentUser: activeUser
});
console.log('return adafter');
return;
}
else {
console.log('Error in retrieving user list :' + err);
}
});
};


ANy other thoughts?



EDIT 2: Actually, the problem seems to lie with the res.render code block. I've been playing around with it and it seems that the code runs res.render once successfully (i.e. with the correct variables displayed), but then immediately runs it again with the undefined variables.



Here is my new console output:



adminFire
return adb4
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is1 undefined
return adafter
GET / 500 2343.440 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|
44| h4 Users who recently liked your work
45| center


EDIT 3: OK, the plot thickens...
Now, I have commented out ALL of my routes so there is no call to render anything.



However, the program still tries to render the 'layout'. I am totally lost now.



Here is my app.js file:



var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// for mongo
require('./app_api/models/db');


var indexRouter = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname,'app_server','views'));
app.set('view engine', 'jade');
app.set('view options', { layout: false });

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));


app.use('/', indexRouter);
app.use('/api', routesApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;


Latest console log:



this is1 undefined
GET / 404 1493.571 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|


EDIT 4:
OK, so i see that the layout file is called by res.render as default. If I remove extends layout from my home page it loads without errors. However, if i then add 'extends layout' the problem comes back. It seems that the app is rendering layout by default, then when i try to render the homepage, which extends layout, it tries to render layout again, and the error returns.



I'm pulling my hair out now.



EDIT 5 added layout.jade above:
Thanks for the help Graham but I still cant seem to get anywhere.










share|improve this question

























  • Thanks for the response Graham. However I added a return statement to the res.render and it hasnt helped. Here is my re.render code:

    – stevo78
    Nov 16 '18 at 23:59











  • I can also see that now, if i remove the 'extends layout' at the top of my template file, then the page renders normally. So the problem seems to lie with the layout or the fact I'm extending it.

    – stevo78
    Nov 17 '18 at 0:07











  • I deleted the line you mentioned above.

    – stevo78
    Nov 17 '18 at 2:01











  • I'm voting to close this question as off-topic because there are at least two issues raised here and neither have the complete relevant code pasted in. This question cannot meet the M, C, or V in MCVE without a complete rewrite.

    – Graham
    Nov 17 '18 at 4:36











  • Please read the help section on how to ask

    – Graham
    Nov 17 '18 at 4:43


















0















The strangest thing. I'm passing a value to a Jade 'variable' and the template reads the variable, as you can see its printed to the console (see 'this is1...this is2 etc') and rendered on the screen. However, the page seems to be getting rendered a second time, at which point the template has lost the value of the variable -> see 'this is1' on the second occurance.



I cant understand why the page is rendering twice. Also, I say its strange as the page appears to renders as normal, it's only when I check the log I can see errors and when I then try to make a request based on one of the variables object IDs it is clear that the template thinks the values of (currentUser) the varables are undefined, Any thoughts? I've been pulling y hair out about this. Thanks:



ROUTE.js:



router.get('/setuser/:id',ctrlPages.setUser);


CONTROLLER.js:



var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports.setUser = (req, res) => {
console.log('req param id', req.params.id);
User.find({_id: ObjectId(req.params.id)}, { new: true }, (err, u
userId) => {
console.log('userid',userId);
if (userId === null) {
console.log('error');
res.redirect('/');
}
else{
console.log('user set');
//currentUser = userId;
res.redirect('/');
}
});
};


TEMPLATE:



extends layout
include _includes/sharedHTMLfunctions
block content
.row.page-header
.col-lg-8
.row
.col-xs-12.col-sm-6
.panel.panel-primary
.panel-heading
h2.panel-title Admin page
- console.log('this is3',currentUser)
.panel-body
.text-center
.jumbotron
h4 This page is for managing users
h4 You will be able to create, delete and change
h4 the current system user. As well as add content.
h4 This will be entirely for black box testing and
h4 will not be acessible once the site is live.

h3 current user:
h2 #{currentUser.userName}
h2 Current users in database:
h3 this data is being supplied in real-time by the model

each user in userList
span.h4 Username:
span.h2= user.userName
- console.log('this is4',user)
p(style='text-align:right')
span.h4 Rating:
span.h2= user.rating
a(href="/setuser/#{user._id}")
button(type="button") set as user



.col-xs-12.col-md-6

h1 Add users
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="userName") user name
.col-xs-12.col-sm-8
input#name.form-control(name="userName")
.form-group
label.col-xs-10.col-sm-2.control-label(for="rating") rating
.col-xs-12.col-sm-2
select#rating.form-control.input-sm(name="rating")
option 10
option 9
option 8
option 7
option 6
option 5
option 4
option 3
option 2
option 1
button.btn.btn-default.pull-right(href="") Add user

h1 Add forum posts to current user
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="topic") post
.col-xs-12.col-sm-8
input#name.form-control(name="topic")


button.btn.btn-default.pull-right(href="") Add post


LAYOUT.jade



doctype html
html
head
meta(name='viewport', content='width=device-width, inital-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/bootstrap.css')
link(rel='stylesheet', href='/bootstrap/css/style.css')
link(rel='stylesheet', href='/bootstrap/css/forum.css')


body
navbar.navbar-defauly.navbar-fixed-top
.container
.navbar-header
a.navbar-brand(href="/home") Create Together
button.navbar-toggle(type="button", data-toggle="collapse", data-target="#navbar-main")
span.icon-bar
span.icon-bar
span.icon-bar
#navbar-main.navbar-collapse.collapse
ul.nav.navbar-nav.navbar-right
li
a(href='/unitplans') Unit planners
li
a(href='/forum') Forum
li
a(href='/helpme') Help me
li
a.selected(href='/') (Admin)
.col-lg-3
.panel.panel-primary
.panel-heading
h2.panel-title User information

.panel-body
.text-center
img(src='/uploads/avatar.jpg', width='200',height=-'300')

span.h4 Username
center
- console.log('this is1',currentUser)
span.h2= currentUser.userName

h4 Users who recently liked your work
center
li.span.h5 mathsGeek82
li.span.h5 algIsBest76
h4 Other site related information
h4 Rating
center
- console.log('this is2',currentUser)
+ratingText(currentUser.rating)
.container
block content
footer
.row
.col-xs-12
small footer

script(src='/javascripts/jquery-3.3.1.js')
script(src='/bootstrap/js/bootstrap.min.js')


CONSOLE log



adminFire
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is3 { userName: 'no user selected', rating: '10' }
this is4 { _id: 5bee3c67194ff91a857ba7ed,
userName: 'me',
rating: 5,
__v: 0 }
this is4 { _id: 5bee3e3953ae361b0f62d2a4,
userName: 'stev',
rating: 4,
__v: 0 }
this is4 { _id: 5bee3e91067d181b2fba359a,
userName: 'bollox',
rating: 8,
__v: 0 }
this is4 { _id: 5bee3eb0067d181b2fba359b,
userName: 'nick',
rating: 10,
__v: 0 }
GET / 200 938.186 ms - 4563
GET /bootstrap/css/bootstrap.css 304 15.842 ms - -
GET /bootstrap/css/style.css 304 10.458 ms - -
GET /bootstrap/css/forum.css 304 2.209 ms - -
GET /uploads/avatar.jpg 304 1.848 ms - -
this is1 undefined
GET /javascripts/jquery-3.3.1.js 404 146.950 ms - 3749
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:43
41| center
42| - console.log('this is1',currentUser)
> 43| span.h2 #{currentUser.userName}
44|
45| h4 Users who recently liked your work
46| center


EDIT:
Thanks Graham, however it didnt help. I added the return statement:



Here is my res.render code:



module.exports.admin = (req, res) => {
// user find by id then set to active user?
User.find((err, userList) => {
console.log('adminFire');
if (!err) {
console.log('return adb4');
res.render('locations-admin', {
title: 'Create Together',
userList: userList,
currentUser: activeUser
});
console.log('return adafter');
return;
}
else {
console.log('Error in retrieving user list :' + err);
}
});
};


ANy other thoughts?



EDIT 2: Actually, the problem seems to lie with the res.render code block. I've been playing around with it and it seems that the code runs res.render once successfully (i.e. with the correct variables displayed), but then immediately runs it again with the undefined variables.



Here is my new console output:



adminFire
return adb4
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is1 undefined
return adafter
GET / 500 2343.440 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|
44| h4 Users who recently liked your work
45| center


EDIT 3: OK, the plot thickens...
Now, I have commented out ALL of my routes so there is no call to render anything.



However, the program still tries to render the 'layout'. I am totally lost now.



Here is my app.js file:



var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// for mongo
require('./app_api/models/db');


var indexRouter = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname,'app_server','views'));
app.set('view engine', 'jade');
app.set('view options', { layout: false });

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));


app.use('/', indexRouter);
app.use('/api', routesApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;


Latest console log:



this is1 undefined
GET / 404 1493.571 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|


EDIT 4:
OK, so i see that the layout file is called by res.render as default. If I remove extends layout from my home page it loads without errors. However, if i then add 'extends layout' the problem comes back. It seems that the app is rendering layout by default, then when i try to render the homepage, which extends layout, it tries to render layout again, and the error returns.



I'm pulling my hair out now.



EDIT 5 added layout.jade above:
Thanks for the help Graham but I still cant seem to get anywhere.










share|improve this question

























  • Thanks for the response Graham. However I added a return statement to the res.render and it hasnt helped. Here is my re.render code:

    – stevo78
    Nov 16 '18 at 23:59











  • I can also see that now, if i remove the 'extends layout' at the top of my template file, then the page renders normally. So the problem seems to lie with the layout or the fact I'm extending it.

    – stevo78
    Nov 17 '18 at 0:07











  • I deleted the line you mentioned above.

    – stevo78
    Nov 17 '18 at 2:01











  • I'm voting to close this question as off-topic because there are at least two issues raised here and neither have the complete relevant code pasted in. This question cannot meet the M, C, or V in MCVE without a complete rewrite.

    – Graham
    Nov 17 '18 at 4:36











  • Please read the help section on how to ask

    – Graham
    Nov 17 '18 at 4:43
















0












0








0








The strangest thing. I'm passing a value to a Jade 'variable' and the template reads the variable, as you can see its printed to the console (see 'this is1...this is2 etc') and rendered on the screen. However, the page seems to be getting rendered a second time, at which point the template has lost the value of the variable -> see 'this is1' on the second occurance.



I cant understand why the page is rendering twice. Also, I say its strange as the page appears to renders as normal, it's only when I check the log I can see errors and when I then try to make a request based on one of the variables object IDs it is clear that the template thinks the values of (currentUser) the varables are undefined, Any thoughts? I've been pulling y hair out about this. Thanks:



ROUTE.js:



router.get('/setuser/:id',ctrlPages.setUser);


CONTROLLER.js:



var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports.setUser = (req, res) => {
console.log('req param id', req.params.id);
User.find({_id: ObjectId(req.params.id)}, { new: true }, (err, u
userId) => {
console.log('userid',userId);
if (userId === null) {
console.log('error');
res.redirect('/');
}
else{
console.log('user set');
//currentUser = userId;
res.redirect('/');
}
});
};


TEMPLATE:



extends layout
include _includes/sharedHTMLfunctions
block content
.row.page-header
.col-lg-8
.row
.col-xs-12.col-sm-6
.panel.panel-primary
.panel-heading
h2.panel-title Admin page
- console.log('this is3',currentUser)
.panel-body
.text-center
.jumbotron
h4 This page is for managing users
h4 You will be able to create, delete and change
h4 the current system user. As well as add content.
h4 This will be entirely for black box testing and
h4 will not be acessible once the site is live.

h3 current user:
h2 #{currentUser.userName}
h2 Current users in database:
h3 this data is being supplied in real-time by the model

each user in userList
span.h4 Username:
span.h2= user.userName
- console.log('this is4',user)
p(style='text-align:right')
span.h4 Rating:
span.h2= user.rating
a(href="/setuser/#{user._id}")
button(type="button") set as user



.col-xs-12.col-md-6

h1 Add users
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="userName") user name
.col-xs-12.col-sm-8
input#name.form-control(name="userName")
.form-group
label.col-xs-10.col-sm-2.control-label(for="rating") rating
.col-xs-12.col-sm-2
select#rating.form-control.input-sm(name="rating")
option 10
option 9
option 8
option 7
option 6
option 5
option 4
option 3
option 2
option 1
button.btn.btn-default.pull-right(href="") Add user

h1 Add forum posts to current user
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="topic") post
.col-xs-12.col-sm-8
input#name.form-control(name="topic")


button.btn.btn-default.pull-right(href="") Add post


LAYOUT.jade



doctype html
html
head
meta(name='viewport', content='width=device-width, inital-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/bootstrap.css')
link(rel='stylesheet', href='/bootstrap/css/style.css')
link(rel='stylesheet', href='/bootstrap/css/forum.css')


body
navbar.navbar-defauly.navbar-fixed-top
.container
.navbar-header
a.navbar-brand(href="/home") Create Together
button.navbar-toggle(type="button", data-toggle="collapse", data-target="#navbar-main")
span.icon-bar
span.icon-bar
span.icon-bar
#navbar-main.navbar-collapse.collapse
ul.nav.navbar-nav.navbar-right
li
a(href='/unitplans') Unit planners
li
a(href='/forum') Forum
li
a(href='/helpme') Help me
li
a.selected(href='/') (Admin)
.col-lg-3
.panel.panel-primary
.panel-heading
h2.panel-title User information

.panel-body
.text-center
img(src='/uploads/avatar.jpg', width='200',height=-'300')

span.h4 Username
center
- console.log('this is1',currentUser)
span.h2= currentUser.userName

h4 Users who recently liked your work
center
li.span.h5 mathsGeek82
li.span.h5 algIsBest76
h4 Other site related information
h4 Rating
center
- console.log('this is2',currentUser)
+ratingText(currentUser.rating)
.container
block content
footer
.row
.col-xs-12
small footer

script(src='/javascripts/jquery-3.3.1.js')
script(src='/bootstrap/js/bootstrap.min.js')


CONSOLE log



adminFire
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is3 { userName: 'no user selected', rating: '10' }
this is4 { _id: 5bee3c67194ff91a857ba7ed,
userName: 'me',
rating: 5,
__v: 0 }
this is4 { _id: 5bee3e3953ae361b0f62d2a4,
userName: 'stev',
rating: 4,
__v: 0 }
this is4 { _id: 5bee3e91067d181b2fba359a,
userName: 'bollox',
rating: 8,
__v: 0 }
this is4 { _id: 5bee3eb0067d181b2fba359b,
userName: 'nick',
rating: 10,
__v: 0 }
GET / 200 938.186 ms - 4563
GET /bootstrap/css/bootstrap.css 304 15.842 ms - -
GET /bootstrap/css/style.css 304 10.458 ms - -
GET /bootstrap/css/forum.css 304 2.209 ms - -
GET /uploads/avatar.jpg 304 1.848 ms - -
this is1 undefined
GET /javascripts/jquery-3.3.1.js 404 146.950 ms - 3749
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:43
41| center
42| - console.log('this is1',currentUser)
> 43| span.h2 #{currentUser.userName}
44|
45| h4 Users who recently liked your work
46| center


EDIT:
Thanks Graham, however it didnt help. I added the return statement:



Here is my res.render code:



module.exports.admin = (req, res) => {
// user find by id then set to active user?
User.find((err, userList) => {
console.log('adminFire');
if (!err) {
console.log('return adb4');
res.render('locations-admin', {
title: 'Create Together',
userList: userList,
currentUser: activeUser
});
console.log('return adafter');
return;
}
else {
console.log('Error in retrieving user list :' + err);
}
});
};


ANy other thoughts?



EDIT 2: Actually, the problem seems to lie with the res.render code block. I've been playing around with it and it seems that the code runs res.render once successfully (i.e. with the correct variables displayed), but then immediately runs it again with the undefined variables.



Here is my new console output:



adminFire
return adb4
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is1 undefined
return adafter
GET / 500 2343.440 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|
44| h4 Users who recently liked your work
45| center


EDIT 3: OK, the plot thickens...
Now, I have commented out ALL of my routes so there is no call to render anything.



However, the program still tries to render the 'layout'. I am totally lost now.



Here is my app.js file:



var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// for mongo
require('./app_api/models/db');


var indexRouter = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname,'app_server','views'));
app.set('view engine', 'jade');
app.set('view options', { layout: false });

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));


app.use('/', indexRouter);
app.use('/api', routesApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;


Latest console log:



this is1 undefined
GET / 404 1493.571 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|


EDIT 4:
OK, so i see that the layout file is called by res.render as default. If I remove extends layout from my home page it loads without errors. However, if i then add 'extends layout' the problem comes back. It seems that the app is rendering layout by default, then when i try to render the homepage, which extends layout, it tries to render layout again, and the error returns.



I'm pulling my hair out now.



EDIT 5 added layout.jade above:
Thanks for the help Graham but I still cant seem to get anywhere.










share|improve this question
















The strangest thing. I'm passing a value to a Jade 'variable' and the template reads the variable, as you can see its printed to the console (see 'this is1...this is2 etc') and rendered on the screen. However, the page seems to be getting rendered a second time, at which point the template has lost the value of the variable -> see 'this is1' on the second occurance.



I cant understand why the page is rendering twice. Also, I say its strange as the page appears to renders as normal, it's only when I check the log I can see errors and when I then try to make a request based on one of the variables object IDs it is clear that the template thinks the values of (currentUser) the varables are undefined, Any thoughts? I've been pulling y hair out about this. Thanks:



ROUTE.js:



router.get('/setuser/:id',ctrlPages.setUser);


CONTROLLER.js:



var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports.setUser = (req, res) => {
console.log('req param id', req.params.id);
User.find({_id: ObjectId(req.params.id)}, { new: true }, (err, u
userId) => {
console.log('userid',userId);
if (userId === null) {
console.log('error');
res.redirect('/');
}
else{
console.log('user set');
//currentUser = userId;
res.redirect('/');
}
});
};


TEMPLATE:



extends layout
include _includes/sharedHTMLfunctions
block content
.row.page-header
.col-lg-8
.row
.col-xs-12.col-sm-6
.panel.panel-primary
.panel-heading
h2.panel-title Admin page
- console.log('this is3',currentUser)
.panel-body
.text-center
.jumbotron
h4 This page is for managing users
h4 You will be able to create, delete and change
h4 the current system user. As well as add content.
h4 This will be entirely for black box testing and
h4 will not be acessible once the site is live.

h3 current user:
h2 #{currentUser.userName}
h2 Current users in database:
h3 this data is being supplied in real-time by the model

each user in userList
span.h4 Username:
span.h2= user.userName
- console.log('this is4',user)
p(style='text-align:right')
span.h4 Rating:
span.h2= user.rating
a(href="/setuser/#{user._id}")
button(type="button") set as user



.col-xs-12.col-md-6

h1 Add users
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="userName") user name
.col-xs-12.col-sm-8
input#name.form-control(name="userName")
.form-group
label.col-xs-10.col-sm-2.control-label(for="rating") rating
.col-xs-12.col-sm-2
select#rating.form-control.input-sm(name="rating")
option 10
option 9
option 8
option 7
option 6
option 5
option 4
option 3
option 2
option 1
button.btn.btn-default.pull-right(href="") Add user

h1 Add forum posts to current user
form.form-horizontal(action="/", method="post", role="form")
.form-group
label.col-xs-10.col-sm-2.control-label(for="topic") post
.col-xs-12.col-sm-8
input#name.form-control(name="topic")


button.btn.btn-default.pull-right(href="") Add post


LAYOUT.jade



doctype html
html
head
meta(name='viewport', content='width=device-width, inital-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/bootstrap.css')
link(rel='stylesheet', href='/bootstrap/css/style.css')
link(rel='stylesheet', href='/bootstrap/css/forum.css')


body
navbar.navbar-defauly.navbar-fixed-top
.container
.navbar-header
a.navbar-brand(href="/home") Create Together
button.navbar-toggle(type="button", data-toggle="collapse", data-target="#navbar-main")
span.icon-bar
span.icon-bar
span.icon-bar
#navbar-main.navbar-collapse.collapse
ul.nav.navbar-nav.navbar-right
li
a(href='/unitplans') Unit planners
li
a(href='/forum') Forum
li
a(href='/helpme') Help me
li
a.selected(href='/') (Admin)
.col-lg-3
.panel.panel-primary
.panel-heading
h2.panel-title User information

.panel-body
.text-center
img(src='/uploads/avatar.jpg', width='200',height=-'300')

span.h4 Username
center
- console.log('this is1',currentUser)
span.h2= currentUser.userName

h4 Users who recently liked your work
center
li.span.h5 mathsGeek82
li.span.h5 algIsBest76
h4 Other site related information
h4 Rating
center
- console.log('this is2',currentUser)
+ratingText(currentUser.rating)
.container
block content
footer
.row
.col-xs-12
small footer

script(src='/javascripts/jquery-3.3.1.js')
script(src='/bootstrap/js/bootstrap.min.js')


CONSOLE log



adminFire
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is3 { userName: 'no user selected', rating: '10' }
this is4 { _id: 5bee3c67194ff91a857ba7ed,
userName: 'me',
rating: 5,
__v: 0 }
this is4 { _id: 5bee3e3953ae361b0f62d2a4,
userName: 'stev',
rating: 4,
__v: 0 }
this is4 { _id: 5bee3e91067d181b2fba359a,
userName: 'bollox',
rating: 8,
__v: 0 }
this is4 { _id: 5bee3eb0067d181b2fba359b,
userName: 'nick',
rating: 10,
__v: 0 }
GET / 200 938.186 ms - 4563
GET /bootstrap/css/bootstrap.css 304 15.842 ms - -
GET /bootstrap/css/style.css 304 10.458 ms - -
GET /bootstrap/css/forum.css 304 2.209 ms - -
GET /uploads/avatar.jpg 304 1.848 ms - -
this is1 undefined
GET /javascripts/jquery-3.3.1.js 404 146.950 ms - 3749
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:43
41| center
42| - console.log('this is1',currentUser)
> 43| span.h2 #{currentUser.userName}
44|
45| h4 Users who recently liked your work
46| center


EDIT:
Thanks Graham, however it didnt help. I added the return statement:



Here is my res.render code:



module.exports.admin = (req, res) => {
// user find by id then set to active user?
User.find((err, userList) => {
console.log('adminFire');
if (!err) {
console.log('return adb4');
res.render('locations-admin', {
title: 'Create Together',
userList: userList,
currentUser: activeUser
});
console.log('return adafter');
return;
}
else {
console.log('Error in retrieving user list :' + err);
}
});
};


ANy other thoughts?



EDIT 2: Actually, the problem seems to lie with the res.render code block. I've been playing around with it and it seems that the code runs res.render once successfully (i.e. with the correct variables displayed), but then immediately runs it again with the undefined variables.



Here is my new console output:



adminFire
return adb4
this is1 { userName: 'no user selected', rating: '10' }
this is2 { userName: 'no user selected', rating: '10' }
this is1 undefined
return adafter
GET / 500 2343.440 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|
44| h4 Users who recently liked your work
45| center


EDIT 3: OK, the plot thickens...
Now, I have commented out ALL of my routes so there is no call to render anything.



However, the program still tries to render the 'layout'. I am totally lost now.



Here is my app.js file:



var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// for mongo
require('./app_api/models/db');


var indexRouter = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname,'app_server','views'));
app.set('view engine', 'jade');
app.set('view options', { layout: false });

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));


app.use('/', indexRouter);
app.use('/api', routesApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;


Latest console log:



this is1 undefined
GET / 404 1493.571 ms - 3747
TypeError: /Users/smyths1/Desktop/Assign2_restart/Assignment_2_clone_After_ASS2_Complete/app_server/views/layout.jade:42
40| center
41| - console.log('this is1',currentUser)
> 42| span.h2= currentUser.userName
43|


EDIT 4:
OK, so i see that the layout file is called by res.render as default. If I remove extends layout from my home page it loads without errors. However, if i then add 'extends layout' the problem comes back. It seems that the app is rendering layout by default, then when i try to render the homepage, which extends layout, it tries to render layout again, and the error returns.



I'm pulling my hair out now.



EDIT 5 added layout.jade above:
Thanks for the help Graham but I still cant seem to get anywhere.







express pug rendering






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 '18 at 2:06







stevo78

















asked Nov 16 '18 at 9:48









stevo78stevo78

11




11













  • Thanks for the response Graham. However I added a return statement to the res.render and it hasnt helped. Here is my re.render code:

    – stevo78
    Nov 16 '18 at 23:59











  • I can also see that now, if i remove the 'extends layout' at the top of my template file, then the page renders normally. So the problem seems to lie with the layout or the fact I'm extending it.

    – stevo78
    Nov 17 '18 at 0:07











  • I deleted the line you mentioned above.

    – stevo78
    Nov 17 '18 at 2:01











  • I'm voting to close this question as off-topic because there are at least two issues raised here and neither have the complete relevant code pasted in. This question cannot meet the M, C, or V in MCVE without a complete rewrite.

    – Graham
    Nov 17 '18 at 4:36











  • Please read the help section on how to ask

    – Graham
    Nov 17 '18 at 4:43





















  • Thanks for the response Graham. However I added a return statement to the res.render and it hasnt helped. Here is my re.render code:

    – stevo78
    Nov 16 '18 at 23:59











  • I can also see that now, if i remove the 'extends layout' at the top of my template file, then the page renders normally. So the problem seems to lie with the layout or the fact I'm extending it.

    – stevo78
    Nov 17 '18 at 0:07











  • I deleted the line you mentioned above.

    – stevo78
    Nov 17 '18 at 2:01











  • I'm voting to close this question as off-topic because there are at least two issues raised here and neither have the complete relevant code pasted in. This question cannot meet the M, C, or V in MCVE without a complete rewrite.

    – Graham
    Nov 17 '18 at 4:36











  • Please read the help section on how to ask

    – Graham
    Nov 17 '18 at 4:43



















Thanks for the response Graham. However I added a return statement to the res.render and it hasnt helped. Here is my re.render code:

– stevo78
Nov 16 '18 at 23:59





Thanks for the response Graham. However I added a return statement to the res.render and it hasnt helped. Here is my re.render code:

– stevo78
Nov 16 '18 at 23:59













I can also see that now, if i remove the 'extends layout' at the top of my template file, then the page renders normally. So the problem seems to lie with the layout or the fact I'm extending it.

– stevo78
Nov 17 '18 at 0:07





I can also see that now, if i remove the 'extends layout' at the top of my template file, then the page renders normally. So the problem seems to lie with the layout or the fact I'm extending it.

– stevo78
Nov 17 '18 at 0:07













I deleted the line you mentioned above.

– stevo78
Nov 17 '18 at 2:01





I deleted the line you mentioned above.

– stevo78
Nov 17 '18 at 2:01













I'm voting to close this question as off-topic because there are at least two issues raised here and neither have the complete relevant code pasted in. This question cannot meet the M, C, or V in MCVE without a complete rewrite.

– Graham
Nov 17 '18 at 4:36





I'm voting to close this question as off-topic because there are at least two issues raised here and neither have the complete relevant code pasted in. This question cannot meet the M, C, or V in MCVE without a complete rewrite.

– Graham
Nov 17 '18 at 4:36













Please read the help section on how to ask

– Graham
Nov 17 '18 at 4:43







Please read the help section on how to ask

– Graham
Nov 17 '18 at 4:43














0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335230%2fcannot-read-property-username-of-undefined-when-trying-to-render-a-jade-templ%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335230%2fcannot-read-property-username-of-undefined-when-trying-to-render-a-jade-templ%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine