gpt4 book ai didi

node.js - 重定向后快速 session 不保存

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:42 25 4
gpt4 key购买 nike

在我的生产应用程序中,将数据保存到 session 然后重定向是完全不可靠的。保存 session 后的 console.log 显示数据已附加。然后在重定向时,另一个 console.log 显示 session 已重置。每 3-5 次尝试, session 将在重定向中持续存在,但它大多不可靠。在我的开发应用程序中,这段代码可以完美运行...

• 我试过更改 express-session 的版本• 我试过将 static 文件夹移动到 server.js 中的 session 中间件之上• 我试过使用 req.session.save()

更新 ******这是 session 中间件的一个已知问题:https://github.com/expressjs/session/pull/69

这是我的 server.js

// Module Dependencies
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var session = require('express-session');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');

// Set Environment from ENV variable or default to development
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = require('./config/config');

// Set Port
var port = process.env.PORT || config.app.port;

// Connect to our MongoDB Database
// mongoose.connect(config.db);

// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));

// Express Session
app.use(session({
secret: 'asfasfa3asfa',
resave: true,
saveUninitialized: true,
cookie: {
secure: false,
maxAge: 2160000000
}
}));

// Favicon
app.use(favicon(__dirname + '/public/img/favicon.ico'));

// Set Jade as the template engine
app.set('views', './app/views');
app.set('view engine', 'jade');

// Get req.body as JSON when receiving POST requests
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({
type: 'application/vnd.api+json'
})); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({
extended: true
})); // parse application/x-www-form-urlencoded

// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));

// routes ==================================================
require('./app/routes')(app); // pass our application into our routes

// start app ===============================================
app.listen(port);
console.log('****** App is now running on port ' + port + ' ******'); // shoutout to the user
exports = module.exports = app; // expose app

这是保存 session 的 Controller :

// Module dependencies.
var config = require('../../config/config');

// Render Either Home Page or Dashboard Page If User is Logged In
var index = function(req, res) {

console.log("Session At Home Page: ", req.session)

if (req.session.user) {
res.render('dashboard');
} else {
res.render('home');
}
};


// Handle Authentication Callback
var callback = function(req, res) {
// Get Access Token via Service-SDK
Service.getAccessToken(req, function(error, tokens) {

if (error) {
console.log(error);
return res.redirect('/');
}

// Otherwise, Save User Data & API Tokens To Session
req.session.regenerate(function(err) {
req.session.user = tokens.user_id;
req.session.access_token = tokens.access_token;
req.session.client_token = tokens.client_token;
req.session.save(function(err) {
console.log("Session Before Redirect: ", req.session);
res.redirect('/');
})
});
});
};

module.exports = {
index: index,
callback: callback
};

我的路线

app.get('/auth/service/callback', application.callback)
app.get('/logout', application.logout);
app.get('/', application.index);

最佳答案

Express 4 中的 livereload 和 express-session 之间存在冲突。您可以在此处阅读更多相关信息 https://github.com/expressjs/cookie-session/issues/14

但简而言之,必须在 session 之后调用 livereload。像这样:

var express     = require("express");
var http = require("http");
var session = require("express-session");
var livereload = require("connect-livereload");

var app = express();
app.set("port", 9090);

/**
* First you must config the session
*/
app.use(session({
secret: "keyboardcat",
name: "mycookie",
resave: true,
saveUninitialized: true,
cookie: {
secure: false,
maxAge: 6000000
}
}));
/**
* Then you can config the livereload
*/
app.use(livereload())

/**
* This simple url should create the cookie.
* If you call the livereload first, the cookie is not created.
*/
app.get("/",function(req,res){
req.session.name = "blaine";
res.end("ok");
});

/**
* If you call the livereload first, the session will always return nothing
* because there is no cookie in the client
*/
app.get("/me",function(req,res){
var name = req.session.name;
var message = "Hello [" + name + "]!";
res.end(message);
});
http.createServer( app ).listen(
app.get("port"),
function(){
console.log("server is running in port ", app.get("port"));
}
)

如果您在 session 配置之前调用 livereload,似乎一切正常,但 cookie 将不会保留。这是一个棘手的错误,我花了一整天的时间。我希望这对某人有所帮助。

关于node.js - 重定向后快速 session 不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com