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

同一域名不同端口下Cookie未正常设置的问题排查与验证

跨端口Cookie设置问题排查与解决

场景说明

  • 本地运行两个应用:
    • NestJS后端(同时托管Angular静态文件):http://localhost:3000
    • Angular开发服务器:http://localhost:4200

问题表现

  • http://localhost:3000登录时,refresh_token Cookie可正常设置
  • http://localhost:4200登录时,Chrome DevTools中看不到Cookie设置,但实际端口间Cookie共享;Postman测试API正常,预检请求无CORS问题,怀疑是Cookie配置或浏览器跨端口处理逻辑导致

后端配置

CORS配置(NestJS)

app.enableCors({
    origin:
      process.env.NODE_ENV === 'production'
        ? process.env.PROD_DOMAIN
        : [
            `http://${process.env.DEV_DOMAIN}:4200`,
            `http://${process.env.DEV_DOMAIN}:3000`,
          ],
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  });

环境变量

PROD_DOMAIN=movies-actors-graph.herokuapp.com
DEV_DOMAIN=localhost

Cookie设置代码(/login端点控制器)

res.cookie('refresh_token', tokens.refresh_token, {
        httpOnly: true,
        sameSite: 'strict',
        secure: true, //!disable if testing on postman
        domain:
          process.env.NODE_ENV === 'production'
            ? process.env.PROD_DOMAIN
            : process.env.DEV_DOMAIN,
        maxAge: parseInt(process.env.JWT_REFRESH_TOKEN_EXPIRATION),
      });

请求响应头对比

来自http://localhost:3000的响应头

Access-Control-Allow-Origin: http://localhost:3000
Connection: keep-alive
Content-Length: 256
Content-Type: application/json; charset=utf-8
Date: Tue, 15 Nov 2022 15:41:59 GMT
ETag: W/"100-...."
Keep-Alive: timeout=5
Set-Cookie: refresh_token=asd123; Max-Age=86400; Domain=localhost; Path=/; Expires=Wed, 16 Nov 2022 15:41:59 GMT; HttpOnly; Secure; SameSite=Strict
Vary: Origin
X-Powered-By: Express

来自http://localhost:4200的响应头

Access-Control-Allow-Origin: http://localhost:4200
Connection: keep-alive
Content-Length: 256
Content-Type: application/json; charset=utf-8
Date: Tue, 15 Nov 2022 15:44:06 GMT
ETag: W/"100-..."
Keep-Alive: timeout=5
Set-Cookie: refresh_token=asd123; Max-Age=86400; Domain=localhost; Path=/; Expires=Wed, 16 Nov 2022 15:44:06 GMT; HttpOnly; Secure; SameSite=Strict
Vary: Origin
X-Powered-By: Express

解决方法

在Angular客户端的请求中添加withCredentials: true配置,示例代码:

//authService
export class AuthService {
  constructor(private http: HttpClient) {}
  refresh() {
    return this.http
      .post(
        environment.backendUrl + '/auth/refresh',
        {},
        {
          withCredentials: true,
        }
      )
      .pipe(shareReplay());
  }
}

将该配置同步应用到/auth/login接口请求后,Cookie可在Chrome DevTools的Application标签正常显示,服务器也能正常接收并处理Cookie。

补充说明

  • 未修改后端的Cookie或CORS配置
  • 推测此问题为Chrome DevTools显示bug,实际功能不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:26:06