node / express会话将对象传递给视图

时间:2015-09-14 21:54:08

标签: node.js express

我有这个帖子登录,它将对象存储在req.locals.user中。

var router = express.Router();
var User = require('../models/user');
var Company = require('../models/company');


/* GET home page. */
router.get('/', function(req, res) {
  res.render('users/login');
});

router.post('/users/login', function(req, res){

  var email = req.body.email;
  var password = req.body.password;

  User.find({email: email, password: password}, function(err, user){
    if(user.length == 0)
    {
      //user wasn't found
      res.render('users/login', {validation: "Invalid Email Or Password"})
    }
    else
    {
      //user was found set session and local objects
      req.session.user = user;
      res.locals.user = user;
      res.redirect('/dashboard');
    }

  });

});

我的问题是当我将用户重定向到仪表板时。我收到一条错误消息,指出我的对象未定义。

<h1 class="page-header">Dashboard v2 <small><%=user.firstName%>.</small></h1>

app.js

    var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var moment = require('moment');
var session = require('express-session');

var dashboard = require('./routes/dashboard');
var users = require('./routes/users');
var categories = require('./routes/categories');
var products = require('./routes/products');
var sales = require('./routes/sales');
var companies = require('./routes/companies');

var app = express();

// set locals
app.locals.moment = moment;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({resave: true, saveUninitialized: true, secret:"mySecretString"}));

    app.use(function(req,res,next){
  res.locals.user = req.session.user;
  delete req.session.user;
  next();
}



app.use('/', dashboard);
app.use('/', users);
app.use('/', categories);
app.use('/', products);
app.use('/', sales);
app.use('/', companies);

app.use(function(req, res, next){

  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "api_key");

  if(req.method == 'OPTIONS') {
    res.send(200);
  }
  else {
    next();
  }

});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });

  mongoose.connect('mongodb://localhost/test');
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

如何在我的观点之间全局传递我的对象?

1 个答案:

答案 0 :(得分:1)

问题,因为重定向(下一个请求)时将删除res.locals.user。只有req.session存在。 用于将变量设置为下一个请求。您需要一个中间件来重新设置本地会话

app.use(function(req,res,next){
 res.locals.user = req.session.user;
 delete req.session.user;
 next();
});