使用express和node.js在ejs模板中插入用户名
我正在尝试在布局中插入用户名,我正在使用带有node和express的ejs模板。我尝试了以下方法:
MongoDB模型:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
var uniqueValidator = require('mongoose-unique-validator')
const bcrypt = require('bcrypt')
const UserSchema = new Schema({
username: {
type: String,
required: [true, 'Please provide username'],
unique: true
},
password: {
type: String,
required: [true, 'Please provide password'],
},
dateRegistered: {
type: Date,
default: new Date()
}
//image: String
});
UserSchema.plugin(uniqueValidator);
//encrypt password
UserSchema.pre('save', function(next) {
const user = this
bcrypt.hash(user.password, 10, (error, hash) => {
user.password = hash
next()
});
});
const User = mongoose.model('User', UserSchema);
module.exports = User
编辑:login.js:
module.exports = (req,res) =>{
res.render('login')
}
编辑:loginUser.js
const bcrypt = require('bcrypt')
const User = require('../models/User')
module.exports = (req, res) => {
const {
username,
password
} = req.body;
User.findOne({
username: username
}, (error, user) => {
if (user) {
bcrypt.compare(password, user.password, (error, same) => {
if (same) {
req.session.userId = user._id
res.redirect('/')
} else {
res.redirect('/auth/login')
}
})
} else {
res.redirect('/auth/login')
}
})
}
编辑:authMiddleware.js:
const User = require('../models/User')
module.exports = (req, res, next) => {
User.findById(req.session.userId, (error, user ) =>{
if(error || !user )
return res.redirect('/auth/login')
next()
})
}
编辑:redirectIfAuthenticatedMiddleware.js
module.exports = (req, res, next) =>{
if(req.session.userId){
return res.redirect('/') // if user logged in, redirect to home page
}
next()
}
编辑:index.js:
const loginController = require('./controllers/login')
const loginUserController = require('./controllers/loginUser')
app.get('/auth/login', redirectIfAuthenticatedMiddleware, loginController)
app.post('/users/login',redirectIfAuthenticatedMiddleware, loginUserController)
navbar.ejs:
<% if(loggedIn) { %>
<p> <%= username %> </p>
<% } %>
结果是一个没有值的空段落
编辑:添加路由,通过控制器管理
解决方案
您的呈现函数在哪里?您需要将变量传递给模板。对于EJS,解决方案是:
路由器处理程序
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
模板页面:index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
因此,在您的情况下,它应该类似于
router.get('/', function(req, res, next) {
res.render('index', {
loggedIn: true
username: res.locals.username
});
});
和那个
<% if(loggedIn) { %>
<p> <%= username %> </p>
<% } %>
相关文章