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

跨源请求携带Cookie:Bun+Elysia环境下CORS配置问题求助

跨域请求携带Cookie失败(Bun + Elysia 环境)解决方案

问题根源

跨域场景下Cookie正常传递需要同时满足三个核心条件:

  • 前端请求明确声明携带凭证(credentials: "include")
  • 后端CORS配置允许接收凭证并指定合法源
  • Cookie本身配置了跨域兼容的属性(SameSite、Secure、Domain)

你的代码缺少后两个关键配置,导致跨域Cookie无法正常传递。


具体修复步骤及代码修改

1. 后端Elysia配置调整

修改CORS插件参数,开启凭证允许并指定前端源,同时设置返回Cookie的跨域属性:

import Elysia from "elysia";
import cors from "@elysiajs/cors";

// 替换为你的前端实际域名/端口,比如前端跑在localhost:5173
const FRONTEND_ORIGIN = "http://localhost:5173";

const app = new Elysia();

app.use(cors({
  origin: FRONTEND_ORIGIN,
  credentials: true // 允许跨域请求携带凭证
}));

app.post("/cookies", ({ cookie: { username, password, icecream } }) => {
  // 打印前端传递的Cookie
  console.log(`username: ${username?.value}, password: ${password?.value}`);

  // 设置返回的Cookie,配置跨域兼容属性
  icecream.value = "chocolate";
  icecream.sameSite = "None";
  icecream.secure = true; // localhost环境下HTTP也可生效,生产环境必须HTTPS
  icecream.domain = "localhost";
});

app.listen(1234);
console.log("Server up and running at http://localhost:1234");

2. 前端代码调整

设置Cookie时添加跨域兼容属性,确保Cookie能被跨域请求携带:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie跨域测试</title>
</head>
<body>
    <form action="post">
        <input type="text" placeholder="username" name="username">
        <input type="text" placeholder="password" name="password">
        <button>submit</button>
    </form>
    <script>
        document.querySelector("form").addEventListener("submit", (e) => {
            e.preventDefault();
            const usernameVal = document.querySelector("input[name='username']").value;
            const passwordVal = document.querySelector("input[name='password']").value;

            // 设置Cookie时添加跨域属性
            document.cookie = `username=${usernameVal}; SameSite=None; Secure; Domain=localhost; Path=/`;
            document.cookie = `password=${passwordVal}; SameSite=None; Secure; Domain=localhost; Path=/`;

            fetch("http://localhost:1234/cookies", {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: "include" // 保持该配置
            })
            .then((response) => {
                console.log(response);
                // 验证是否收到后端返回的Cookie
                console.log("当前Cookie:", document.cookie);
            });
        })
    </script>
</body>
</html>

关键配置说明

  • 后端CORS的credentials: true:必须开启,否则浏览器会拦截跨域请求携带的Cookie
  • origin指定具体源:不能用*,因为*和credentials: true冲突,必须明确前端的域名/端口
  • Cookie的SameSite=None:允许Cookie在跨域场景下被发送,必须配合Secure属性(localhost环境例外)
  • Secure属性:要求Cookie仅通过HTTPS传输,生产环境必须配置,localhost下HTTP也可正常使用

内容的提问来源于stack exchange,提问作者Theo Zibell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:43:14