简体   繁体   English

使用 express 和 node.js 在 ejs 模板中插入用户名

[英]Insert username in a ejs template with express and node.js

I'm trying to insert the username in a layout, I'm using ejs templating with node and express.我正在尝试在布局中插入用户名,我正在使用带有 node 和 express 的 ejs 模板。 I've tried the following:我尝试了以下方法:

Mongodb model: Mongodb model:

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

EDIT: login.js:编辑:login.js:

module.exports = (req,res) =>{
  res.render('login')
}

EDIT: loginUser.js编辑: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')
    }
  })
}

EDIT: authMiddleware.js:编辑: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()
    })
}

EDIT: redirectIfAuthenticatedMiddleware.js编辑:redirectIfAuthenticatedMiddleware.js

module.exports = (req, res, next) =>{
    if(req.session.userId){
      return res.redirect('/') // if user logged in, redirect to home page
    }
    next()
}

EDIT: index.js:编辑: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:导航栏.ejs:

<% if(loggedIn) { %>
    <p> <%= username %> </p>
<% } %>

The result is an empty paragraph with no value EDIT: added routes, managed through controllers结果是一个没有值的空段落编辑:添加的路由,通过控制器管理

where is your render function?你的渲染 function 在哪里? You need to pass the variable to the template.您需要将变量传递给模板。 For that, with EJS the solution is:为此,使用 EJS 的解决方案是:

router handler路由器处理程序

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

in the template page: index.ejs在模板页面: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>

so in your case it should be something like所以在你的情况下它应该是这样的

router.get('/', function(req, res, next) {
  res.render('index', { 
      loggedIn: true
      username: res.locals.username 
  });
});

and that然后

<% if(loggedIn) { %>
    <p> <%= username %> </p>
<% } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM