问题描述
围绕此主题有很多问题,但是没有一个可以解决我的问题,我开发了一个快速应用程序,我的身份验证方法是写入会话对象并使用redis-store.在开发过程中效果很好,
there were many questions about this topic around , but none could solve my problem ,i developed an express app and my authentication method was to write to session object and using redis-store . it worked perfect during development ,
但是,当我第一次部署我的站点进行一些测试(使用模数)时,我得到一个错误,指出req.session是不确定的.当我在localhost上运行此代码时,代码仍然可以正常工作.
but the first time i deployed my site for some tests ( using modulus ) i get an error that req.session is undefined . the code still works fine when i run this on localhost .
这实际上是我的第一个Web项目,有很多我不知道并且必须通过学习的明显要点和技巧.也许我在这里错过了一些简单而明显的事情,不知道!
this is actually my first web project and there were so many obvious points and tricks that i didn't know and had to learn through the way . maybe i'm missing something simple and obvious here , don't know !
package.josn依赖项:
"dependencies" : {
"express" : "~3.4.4",
"mongoose" : "~3.6.2",
"socket.io":"1.x" ,
"bcrypt-nodejs" : "0.0.3",
"connect-redis": "1.4.x" ,
"body-parser" : "1.4.3" ,
"cookie-parser": "~1.0.0",
"express-session": "~1.0.0"
} ,
应用配置
var express = require('express') ;
var app = express() ;
var http = require('http') ;
var io = require('socket.io') ;
var bodyParser = require('body-parser');
var mongoose = require('mongoose') ;
var mongoose1 = require('mongoose') ;
var bcrypt = require('bcrypt-nodejs') ;
var PORT = process.env.PORT || 8080 ;
var server = http.createServer(app) ;
var RedisStore = require('connect-redis')(express);
app.configure(function () {
app.use(express.static(__dirname + "/static" )) ;
app.use( express.cookieParser() );
app.use(express.bodyParser()) ;
app.use(express.session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
pass: '****'
}),
secret: '12345qwr'
})
);
}) ;
,当我到达服务器中的req.session.[]时,应用程序崩溃并重新启动,因为req.session在undefined中.例如,当我单击登录按钮并将帖子请求发送到"/api/login"或..
and when i reach req.session.[] in my server , app crashed and restarts because req.session in undefined .for example when I click on a login button and a post request is sent to "/api/login" or ..
app.post('/api/login' , function (req, res) {
UserDBModel.findOne({ username : req.body.user } , function (err, user) {
if (err) { res.json(err) ; }
if ( user ) {
if ( bcrypt.compareSync( req.body.pass , user.password ) ) {
req.session.Auth = { username : user.username , password : user.password } ;
//app crashes here with error : TypeError: Cannot set property 'Auth' of undefined
}) ;
ps.为了进行身份验证,我在会话中存储了一个"Auth"对象,其中包含用户名和已登录用户的哈希密码.
ps. to authenticate , i store an "Auth" object in my session containing username and hashed password of logged in users .
推荐答案
而不是 app.use(express.session(
)尝试使用: app.use(express.cookieSession());
,则可以访问 request.session
对象...
Instead of app.use(express.session(
try to use: app.use(express.cookieSession());
then the request.session
object will be accessible...
这篇关于request.session未定义.nodeJS Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!