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

Symfony集成Mercure时无法发送Cookie问题求助

问题诊断

Firefox返回400 Bad Request的核心原因是Mercure订阅请求缺少必填的topic参数,同时跨域Cookie的配置存在疏漏,导致浏览器拒绝接受Cookie。


具体修复步骤

1. 补全客户端订阅的Topic参数

Mercure要求订阅请求必须通过topic参数指定监听主题,你的代码中定义了主题地址但未添加到请求URL中,这是触发400错误的直接原因。修改客户端代码如下:

<script>
const url = new URL("https://localhost/.well-known/mercure");
// 向Mercure订阅URL添加topic参数
url.searchParams.append('topic', 'https://127.0.0.1:8000/instrumenthol');
const eventSource = new EventSource(url, {
    withCredentials: true,
});
eventSource.onmessage = (e) => {
    console.log(e.data);
    document.getElementById("message").insertAdjacentHTML('afterend', '<div class="alert alert-success">Ping</div>');
    window.setTimeout(() => {
        const alert = document.querySelector('.alert');
        if (alert) alert.parentNode.removeChild(alert);
    }, 50000);
}
</script>

2. 修正跨域Cookie配置

你设置了SAMESITE_NONE,但需要调整以下两点:

  • 明确指定domain参数:localhost和127.0.0.1被浏览器判定为不同域,需统一Cookie的作用域
  • 确保HTTPS环境:Secure属性要求Cookie只能在HTTPS下传递,需保证应用服务器和Mercure服务器都启用HTTPS(本地环境需配置有效证书)

修改服务端Cookie创建代码:

public function returnNotification(HubInterface $hub, string $message, string $userIdd){
    $userId = Uuid::fromString($userIdd);
    $userIdCookie = new Cookie(
        'user_id', 
        $userId, 
        0, 
        '/', 
        'localhost', // 明确指定domain,适配跨域场景
        true, // 保持Secure属性,需HTTPS支持
        true, 
        false,
        Cookie::SAMESITE_NONE
    );
    $update = new Update(
        "https://127.0.0.1:8000/instrumenthol",
        json_encode(['status' => $message]),
        true,
        $userIdCookie
    );
    $hub->publish($update);
    return new Response('published!');
}

3. 验证Mercure服务器配置

检查Mercure服务器的ALLOWED_ORIGINS配置,必须包含你的应用域名(https://127.0.0.1:8000),否则会拒绝跨域请求。示例启动命令:

mercure --jwt-secret='your-secret-key' --allowed-origins='https://127.0.0.1:8000'

4. 浏览器端验证

修复后,在Firefox开发者工具的「网络」面板中检查:

  • 确认https://localhost/.well-known/mercure请求已携带topic参数
  • 查看请求头的Cookie字段,确认user_id已被正确传递
  • 查看响应头的Set-Cookie,确认SameSite=None; Secure属性配置正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:15:50