You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js后端发送的Cookie无法在浏览器中存储的问题求助

问题解决:跨域场景下Node.js后端Cookie无法在浏览器存储

核心原因

浏览器的同源策略默认限制跨域请求的Cookie处理,你的代码缺少两个关键配置:

  1. 后端CORS未开启凭证支持且未指定合法源
  2. 前端fetch请求未声明携带凭证

修改后的代码

后端代码

const express = require('express')
const cookieParser = require('cookie-parser')
const cors = require('cors')
const app = express();

app.listen(8080,()=>{
    console.log("express running on port 8080")
})

app.use(cookieParser())
// 配置CORS:指定前端实际地址,允许凭证传递
app.use(cors({
  origin: 'http://localhost:5500', // 替换为你的前端运行域名/端口
  credentials: true
}))

app.get('/login',(req,res)=>{
    res.cookie('cookies','myid',{
        httpOnly: true,
        sameSite: 'lax', // 本地HTTP环境使用该值,线上HTTPS可改为'none'并开启secure
        // secure: true, // 线上HTTPS环境启用
        maxAge: 24 * 60 * 60 * 1000 // 可选:设置Cookie有效期1天
    }).json({msg:"cookies sended ! "})
})

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="myfunction()">Fetch</button>

    <script>
        const myfunction = async ()=>{
        let res = await fetch('http://localhost:8080/login',{ 
            method:"GET",
            credentials: 'include' // 关键:允许携带和保存跨域Cookie
        })
        res = await res.json()
        console.log(res)
        }
    </script>
</body>
</html>

关键配置说明

  • 后端CORS:必须指定具体的origin(不能用*,否则浏览器会拒绝凭证传递),同时设置credentials: true,告知浏览器该跨域源允许处理Cookie
  • 前端fetch:添加credentials: 'include',表示请求时携带现有Cookie,并且允许保存响应返回的新Cookie
  • Cookie的sameSite属性:
    • 本地HTTP开发环境:使用lax或strict,不能用none(该选项要求配合secure: true,仅HTTPS环境生效)
    • 线上HTTPS环境:可设置sameSite: 'none'并开启secure: true,确保跨域场景下Cookie正常存储和携带

内容的提问来源于stack exchange,提问作者DIPAK JAWKAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:33:37