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

微服务间GraphQL请求浏览器未生成Cookie问题排查

问题分析与解决方案

核心原因

通过Gateway(4000端口)请求时浏览器不设置Cookie,主要源于两个关键问题:

  1. GraphQL Mesh默认不会转发上游服务返回的Set-Cookie响应头,导致浏览器无法接收设置Cookie的指令
  2. Auth服务的CORS配置未允许Gateway域名,且Cookie的SameSite属性为Strict,不符合跨端口(跨域)场景的浏览器安全策略

解决方案

1. 更新Auth服务的CORS配置

Auth服务当前仅允许http://localhost:3000的请求,需添加Gateway的域名http://localhost:4000:

// app.ts(Auth服务)
export const yoga = createYoga({
  // ...其他原有配置
  cors: {
    origin: ['http://localhost:3000', 'http://localhost:4000'], // 允许两个域名
    credentials: true,
    allowedHeaders: ['X-Custom-Header'],
    methods: ['POST']
  }
});

2. 配置GraphQL Mesh转发Set-Cookie响应头

在.meshrc.yaml的Auth源配置中,明确指定转发上游的Set-Cookie头到客户端:

# .meshrc.yaml
sources:
  - name: Auth
    handler:
      graphql:
        endpoint: http://localhost:3000/graphql
        responseHeaders:
          - Set-Cookie # 转发Set-Cookie头
plugins:
  - httpDetailsExtensions:
      if: "env.NODE_ENV === 'development'"
pollingInterval: 3600000
serve:
  playground: true
  hostname: 0.0.0.0
  cors:
    credentials: true
    origin: http://localhost:4000

3. 调整Cookie的SameSite属性

Strict模式会阻止跨端口场景下的Cookie设置,修改为Lax适配开发环境:

// session.ts
export function setCookie(ctx: GraphQLContext, name: TokenType, token: string, expires: string | number) {
  ctx.request.cookieStore?.set({
    name,
    sameSite: 'Lax' as CookieSameSite, // 修改为Lax模式
    secure: en(COOKIES_SECURE),
    domain: COOKIES_DOMAIN!,
    expires: new Date(Date.now() + ms(expires.toString())),
    value: token,
    httpOnly: en(COOKIES_HTTPONLY)
  });
}

验证步骤

  1. 重启Auth服务和Gateway服务
  2. 通过http://localhost:4000/graphql执行登录mutation
  3. 打开浏览器开发者工具的Application面板,检查Cookies下的localhost是否存在accessToken和refreshToken

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 04:00:54