最奇怪的事情。我将一个值传递给Jade'变量',并且模板读取该变量,如您所见,它已打印到控制台(请参阅“ this is1 ... this is2等”)并呈现在屏幕上。但是,该页面似乎正在第二次呈现,这时模板丢失了变量的值->在第二次出现时看到'this is1'。
我不明白为什么页面要渲染两次。另外,我说这很奇怪,因为页面似乎可以正常显示,只有当我检查日志时才能看到错误,然后我尝试根据其中一个变量对象ID发出请求时,模板显然认为(currentUser)变量的值未定义,有什么想法吗?我一直在为此扯头发。谢谢:
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('/');
}
});
};
模板:
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')
控制台日志
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
编辑: 谢谢格雷厄姆,但是没有帮助。我添加了return语句:
这是我的渲染代码:
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);
}
});
};
还有其他想法吗?
编辑2:实际上,问题似乎出在res.render代码块上。我一直在使用它,似乎代码成功运行了一次res.render(即显示正确的变量),但是随后立即使用未定义的变量再次运行它。
这是我的新控制台输出:
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
编辑3:好,情节变厚... 现在,我已注释掉所有路线,因此无需调用即可渲染任何内容。
但是,程序仍然尝试渲染“布局”。我现在完全迷路了。
这是我的app.js文件:
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;
最新的控制台日志:
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|
编辑4: OK,所以我看到默认情况下res.render调用了布局文件。如果我从主页上删除扩展布局,则会加载而不会出现错误。但是,如果我再添加“扩展布局”,问题就会再次出现。看来该应用程序默认情况下正在渲染布局,然后当我尝试渲染扩展布局的主页时,它将尝试再次渲染布局,并返回错误。
我现在正在拔头发。
编辑5在上面添加了layout.jade: 感谢格雷厄姆(Graham)的帮助,但我似乎还是一无所获。