尽管成功发送到前端,但仍无法存储 cookie - Express 和 React 设置

Unable to Store Cookies despite Successful Sending to Frontend - Express and React Setup

提问人:Nyxz 提问时间:11/16/2023 最后编辑:Amit MohantyNyxz 更新时间:11/19/2023 访问量:25

问:

我在服务器上托管我的网站时遇到了问题。尽管已成功将 cookie 发送到前端,但我无法存储它们。

以下是我的设置概述:我在后端使用 Express,在前端使用 React。下面是我的代码片段:

索引.js

async function connectToDatabase() {
    try {
        await connection.authenticate();
        console.log('Connection to database successful');
    } 
    catch (error) {
        console.error('Error connecting to database:', error);
    }
}
connectToDatabase();
  
 app.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,UPDATE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});
  
const privateKey = fs.readFileSync("??");
const certificate = fs.readFileSync("??");
const credentials = { key: privateKey, cert: certificate };
const httpsServer = https.createServer(credentials, app);

app.use(cors({ credentials: true, origin: 'https://??'}));
app.use(cookieParser());
app.use(express.json());
app.use(router);

const refreshToken = jwt.sign({ shop_id }, process.env.REFRESH_TOKEN_SECRET, {
   expiresIn: "1d",
});

res.cookie("refreshToken", refreshToken, {
   httpOnly: true,
   maxAge: 24 * 60 * 60 * 1000,
   secure: true,
   path: '/',
   sameSite: "none",
   domain: "??",
});

httpsServer.listen(??, () => console.log("Server is running on port ??"));

我已经确保 CORS 标头已正确设置并尝试了各种配置,但 cookie 未存储在浏览器中。

尽管进行了广泛的研究和尝试,但这些 cookie 并没有持续存在。关于可能导致此问题的原因以及如何解决该问题的任何指导或建议将不胜感激。谢谢!

JavaScript ReactJS Express setCookie

评论

0赞 Wiktor Zychla 11/16/2023
最有可能的是,您将 cookie 设置为 but navigate to the site via 而不是 .securehttphttps

答: 暂无答案