gpt4 book ai didi

javascript - Express.js跨域 session 不保存

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:48 29 4
gpt4 key购买 nike

我正在尝试制作第三方应用程序,这意味着它将跨多个域运行。我想处理使用该应用程序的每个用户的 session ,因此,我使用了express-session模块来制作它,但每次我发出请求时,它都会为当前请求启动一个新 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) {},
})

``

最佳答案

fetch 调用中使用 credentials: 'include',否则 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/

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