如何在nodejs中读取从req.session加载的数组的长度?

时间:2014-12-02 14:28:03

标签: arrays node.js session express

我的帖子请求中的代码如下所示:

var titles = [];
        movies.forEach(function(movie) {

            // If title exists in array, dont push.
            if(titles.indexOf(movie.title) > -1){
                console.log('skipped duplicate title of '+movie.title);

            }
            else{
                titles.push(movie.title);
                console.log('pushed '+movie.title);
            }
        });

        req.session.titles = titles;
        console.log(req.session.titles);

我的获取请求如下所示:

app.get('/search', function(req, res) {
    var arr = req.session.titles;
    if(arr.length > 0) {
    //do something
}

但我收到错误TypeError: Cannot read property 'length' of undefined at Object

我的server.js看起来像这样。我不认为会议正在发挥作用。我做错了什么? 我想我以前有会议工作,我已经安装了所有软件包..

我的req.session.titles在评论中是空的。

// server.js

// set up ======================================================================
// get all the tools we need
var express  = require('express');
var app      = express();
var port     = process.env.PORT || 3003;
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var fs       = require('fs');
var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var session      = require('express-session');
//var Parse = require('../app/models/parse');

var configDB = require('./config/database.js');

// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({
  secret: 'hakunamatata',
  resave: false,
  saveUninitialized: true
}));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// set the default tmpdir for uploads (IMPORTANT)
process.env.TMPDIR = './tmp';

//load all files in models dir
fs.readdirSync(__dirname + '/app/models').forEach(function(filename) {
    if (~filename.indexOf('js')) require(__dirname + '/app/models/' + filename)
});

// launch ======================================================================
app.listen(port);

2 个答案:

答案 0 :(得分:0)

我可以在行var titles = []中看到一个肯定的错误; 在这里你实际上每个帖子请求删除标题。你应该做的是写

var titles = req.session.titles || [];

你也执行app.use(cookieParser());两次。

不要认为修复这两个错误会解决问题,但无论如何都会解决问题。

答案 1 :(得分:0)

问题不在我的会话中,而是在omdb api读取数据到会话变量之前执行的get请求中。所以在我尝试访问它之前没有设置会话变量。

我使用回调函数来解决这个问题。

该问题的链接以及我如何解决它是here