我面临的问题是:在每个请求中都会创建新的sessionID。有人会对此嗤之以鼻吗?
我正在使用的版本:
节点版本:v6.10.3 NPM版本:3.10.10 [email protected] [email protected]
如果我没有专门设置cookie,那么maxAge的默认值是多少?不确定是否需要。
您是否看到以下代码存在任何问题?我被困了,请帮助。
var app = express();
app.use(express.static(path.join(__dirname, 'landing')));
app.use(bodyparser.json());
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {secure: true}
}))
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'landing', 'index.html'));
});
var contextPath = '/myportal';
//UI url
app.get(contextPath, function (req, res) {
var reqValues;
logger.info("req sessionID is :::" + req.sessionID);
// do something
}
app.use(express.static(path.join(__dirname, 'build'))); //react UI path
res.sendFile(path.join(__dirname, 'build', 'index.html'));
}
//health check url
app.get(contextPath + '/health', function (req, res) {
logger.info("env is " + env);
logger.info("myportal health is ok");
res.send('Health Ok!\n');
});
如果还有人在寻找答案。 (经过大量工作后,代码为我工作。如果我错了,请纠正我)
原因:快递会话在cookie中存储sessionID,它将在后端(服务器)中设置前端的cookie(浏览器,你可以在浏览器中看到名为connect.sid的cookie)。每当来自浏览器的任何请求首先它将检查该cookie(存储sessionID)。如果它找到cookie它不会创建新会话,否则它将再创建一个新会话。(你可以通过记录req来检查它)请求中的.sessionID)
解决方案:为了克服这一点,我们从前端(浏览器)发出的每个请求都要将cookie发送到后端(服务器)。服务器将自动解析cookie,不会为每个请求创建任何新会话。
我正在使用axios进行请求调用,其中对于我添加的每个请求{withCredentals:true},以便浏览器可以将cookie发送到后端服务器(自动)。以下代码为我工作。
app.js
require('dotenv').config({path:'./config.env'});
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors=require('cors');
const uuid = require('uuid/v4')
const cookieParser = require('cookie-parser');
const session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(cors({
origin:[process.env.ORIGIN],//frontend server localhost:8080
methods:['GET','POST','PUT','DELETE'],
credentials: true // enable set cookie
}));
app.use(cookieParser(process.env.SESSIONSECRET)); // any string ex: 'keyboard cat'
app.use(session({
secret: process.env.SESSIONSECRET,
store:new FileStore,
cookie:{
maxAge:36000,
httpOnly:false,
secure:false // for normal http connection if https is there we have to set it to true
},
resave: false,
saveUninitialized: true
}))
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
res.header("Access-Control-Allow-Origin", process.env.ORIGIN);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content- Type, Accept, Authorization");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// rest of code is your mongo connection
axios休息电话::
axios.defaults.withCredentials = true;
axios.get('http://localhost:8080/getDetails',{
headers:{
withCredentials:true,
}
});