main.js(仅限相关部分)
var express = require('express');
var app = require('express')(),
expressSession = require('express-session'),
cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// Access Middleware
var connect = require('connect');
var http = require('http');
var session = require('express-session');
app.use(express.static('public'));
app.use(expressSession({
secret: 'SECKEY',
resave: true,
saveUninitialized: true
}));
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
var response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
var post = req.body;
if(post.first_name === 'u' && post.last_name === 'p') {
res.session.user_id = 3;
res.redirect('/home');
} else {
res.send('INVALID');
}
res.end(JSON.stringify(response));
});
这是我得到的错误:
TypeError: Cannot set property 'user_id' of undefined
at D:\Users\Winston\Code\NodeJS Projects\Sample\main.js:43:29
at Layer.handle [as handle_request] (D:\Users\Winston\Code\NodeJS Projects\Sample\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Users\Winston\Code\NodeJS Projects\Sample\node_modules\express\lib\router\route.js:131:13)
at D:\Users\Winston\Code\NodeJS Projects\Sample\node_modules\body-parser\lib\read.js:121:5
at invokeCallback (D:\Users\Winston\Code\NodeJS Projects\Sample\node_modules\body-parser\node_modules\raw-body\index.js:262:16)
at done (D:\Users\Winston\Code\NodeJS Projects\Sample\node_modules\body-parser\node_modules\raw-body\index.js:251:7)
at IncomingMessage.onEnd (D:\Users\Winston\Code\NodeJS Projects\Sample\node_modules\body-parser\node_modules\raw-body\index.js:308:7)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
req.session没有工作,但我认为我定义了一切。我已经安装了connect和express-session中间件。我怎样才能在将来调试这样的问题?
编辑1:打印出req.session
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
{ first_name: 'u', last_name: 'p' }
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
答案 0 :(得分:3)
您正在呼叫res.session
而不是req.session
答案 1 :(得分:1)
您在下面更改了代码:
res.session.user_id = 3;
到
req.session.user_id = 3;