我会像这样配置express-session插件:
var express = require('express'),
session = require('express-session'),
uuid = require('node-uuid');
var expiration_day = new Date('9/15/2015'),
today = new Date(),
session_life = Math.abs(expiration_day.getTime() - today.getTime());
var config = {
name: 'mycookie', // session ID cookie name
key: 'mycookie', // session ID cookie name
secret: '$FGDFH$W#WEgfgdf',
hash: {
salt: '9883hjHFIDSU&U#H'
},
store: new MongoStore({mongooseConnection: db}),
unset: 'keep', //never remove expired sessions
saveUninitialized: true, //always create session, even if nothing is stored
resave: false, //don't save session if unmodified
ttl: session_life,
autoRemove: 'disabled', //disable expired sessions cleaning
genid: function (req) {
"use strict";
return uuid.v4();
},
cookie: {
path: '/api', // cookie will be stored for requests under '/api'
httpOnly: false,
domain: 'example.com',
secure: false,
expires: expiration_day,
maxAge: session_life
}
};
app.sessionMW = session(config);//session middleware
在Chrome和Mozilla Firefox浏览器中,只为用户创建一个会话。该会话可用于使用sessionMW中间件的所有路由。因此,如果您对/api/users/或/api/sessions进行GET或POST请求,则相同的会话ID将存储在cookie中,并在每个请求的cookie标头中发送。
Internet Explorer不是这样工作的。 对于每个请求,都会创建一个新的会话。会话存储在服务器上,我已确认应用程序的每个路由在浏览器中都有一个新的cookie。
我已定义了cookie中的域、路径和过期时间。 IE中的cookie显示这些值。
我没有使用cookieParser,所以那不可能是问题。
无论如何,问题似乎出现在客户端。 Internet Explorer未随请求发送Cookie标头。它接收到每个请求的set-cookie标头响应。但数据从未在后续请求中重复使用。
这可能是CORS问题吗?该cookie不属于我运行应用程序的同一域。我需要在另一个域上托管的所有API路由上使用会话。
客户端已配置为在CORS请求中包含cookie。
$.ajaxSetup({
cache: false,
xhrFields: {
withCredentials: true //all AJAX requests should include Cookie data
}
});
我在响应中发送这些接受控制头:
为什么IE不在请求中设置Cookie标头? 该域名没有下划线,并且不以数字开头。Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type,
Accept Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH
Access-Control-Allow-Origin: http://example.com