问题描述
我正在尝试在布局中插入用户名,我正在使用带有node和express的ejs模板。我尝试了以下方法:
MongoDB模型:
编辑:login.js: 编辑:loginUser.js 编辑:authMiddleware.js: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
module.exports = (req,res) =>{
res.render('login')
}
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')
}
})
}
编辑:redirectIfAuthenticatedMiddleware.jsconst 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()
})
}
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>
<% } %>
这篇关于使用express和node.js在ejs模板中插入用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!