我正在尝试制作第三方应用程序,这意味着它将跨多个域运行。
我想为使用该应用程序的每个用户处理一个会话,因此,我使用express-session模块来实现它,但是每次发出请求时,它都会为当前请求启动一个新的会话...

const express    = require('express'),
      router     = express.Router();
      const session = require('express-session')

router.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

router.use(session({
    secret: 'keyboard cat',
    resave: true,
    maxAge: 2 * 60 * 60 * 1000, // 2 hours
    saveUninitialized: false,
    cookie: {
        maxAge:  2 * 60 * 60 * 1000 ,
        secure: false,
        sameSite : false,
        httpOnly: false}
}))
router.get( '/',function (req, res, next) {

    // let payload = req.query;
    let isDevClient = req.session.isDevClient  || false;
    console.log('isNew? ', isDevClient );
    res.status(201).send({
        success: true,
        isDevClient,
        message: 'msg..'
    });

}).post( '/',function (req, res, next) {
    let payload = req.body;
    console.log('isNew? ', req.session.isDevClient )
    req.session.isDevClient = true;
    res.status(200).send({
        success: true,
        message: 'ok'
    });
});


module.exports = router;



请求示例

// javascript
fetch('https://127.0.0.1:8443/',{
method : "POST",
credentials: 'include',
})

//Jquery
    $.ajax({
        'type': 'post',
        'url': 'https://127.0.0.1:8443',
         'xhrFields': {
         'withCredential's: true
         }
        'success': function (response) {},
    })

``

最佳答案

credentials: 'include'调用中使用fetch,否则fetch在跨域请求期间将不会发送cookie。例:

fetch(..., {
   ...,
   credentials: 'include'
}


更新:如果未设置SameSite属性,则最新的Chrome版本似乎不会在跨域请求期间发送Cookie。

设置sameSite : 'none'应该可以修复它。请注意,chrome也需要这些Cookie才能确保安全。 https://www.chromestatus.com/feature/5633521622188032

顺便说一下,您可以轻松提供带有repl.it的示例(例如this

关于javascript - Express.js跨域 session 未保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60376620/

10-12 12:21