在Internet Explorer中使用Express-session

10

我会像这样配置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
    }
});

我在响应中发送这些接受控制头:

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

为什么IE不在请求中设置Cookie标头? 该域名没有下划线,并且不以数字开头。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-withcredentials - robertklep
3个回答

2

如果您使用fetch,请确保将凭据设置为include

fetch('/url/', { credentials: 'include' });

否则,在IE Edge中,会话ID将不会随请求一起包含。

1
请确保您的服务器时区和时间正确。 我刚刚解决了一个问题,其中服务器的时间是本地时间,但时区设置为UTC。 不知何故,Chrome和Firefox仍然正确解释了过期时间,但IE遵守了UTC时区,因此在它的眼中,cookie已经过期了。 请注意,仅当您处于相对于UTC的负时区时,它才会立即过期。

0

在您的域名中使用下划线也可能导致此问题。

IE和Edge不会存储包含下划线的域名的cookie。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接