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

Starlette CORSMiddleware无法在浏览器设置Cookie,仅Postman生效

问题排查与修复步骤

1. 调整中间件注册顺序

当前代码中CORSMiddleware先于SessionMiddleware注册,这会导致Session设置的Cookie头无法被CORSMiddleware正确处理。Starlette/FastAPI的中间件执行逻辑是后添加的先执行,因此需要将SessionMiddleware放在CORSMiddleware之前注册:

# 优先注册SessionMiddleware
app.add_middleware(SessionMiddleware, secret_key="some-random-string")
# 再注册CORSMiddleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:3000",
        "http://127.0.0.1:3000",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

2. 配置SessionMiddleware的Cookie跨域属性

默认情况下,SessionMiddleware设置的CookieSameSite属性为Lax,跨域场景下浏览器会阻止这类Cookie写入。需要显式调整Cookie属性:

app.add_middleware(
    SessionMiddleware,
    secret_key="some-random-string",
    same_site="none",
    secure=True,
    # 若需子域名共享Cookie,可添加domain参数,例如domain=".localhost"
)

注:secure=True要求HTTPS环境,但localhost下浏览器会允许例外,生产环境必须部署HTTPS才能生效。

3. 排除自定义中间件干扰

你的process_auth自定义中间件目前仅打印Session信息,不会直接影响Cookie设置,但后续扩展时需注意:不要修改或移除响应头中的Set-Cookie字段。

4. 前端配置二次确认

虽然你已设置withCredentials: true,仍需确认:

  • Axios需确保每个跨域请求都携带该配置(或全局配置):
    axios.get('http://localhost:8000/set/test', { withCredentials: true })
    
  • 打开浏览器控制台的Network标签,检查请求的Response Headers是否包含Access-Control-Allow-Credentials: true,以及Set-Cookie头是否存在。

为什么Postman可以正常工作?

Postman不受浏览器的跨域安全策略约束,它会自动保存并发送Cookie,无需遵循SameSite、CORS等浏览器端规则,因此请求能正常生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:45:17