我的代码在我的帖子请求中如下所示:
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);
最佳答案
我肯定在行var title = []中看到一个错误;
在这里,您实际上在每个帖子请求中都删除标题。你应该做的就是写
var titles = req.session.titles || [];
您也执行app.use(cookieParser());两次。
不要认为解决这两个错误会解决问题,但是无论如何他们都会解决。
关于arrays - 如何读取从Node.js的req.session加载的数组的长度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27251802/