React+Vite+FastAPI环境下Cookie无法存储问题求助
核心问题分析
你的配置存在两处关键错误,导致浏览器拒绝存储Cookie:
- Cookie的Domain参数格式错误:后端设置的
domain='http://localhost:5173'包含了HTTP协议,而Cookie的Domain字段仅允许域名/IP+端口(或纯域名),不能带协议前缀。 - Vite代理未开启Credentials传递:当前代理配置没有设置
withCredentials: true,导致代理服务器转发请求时会丢弃Cookie相关的头信息,浏览器无法正确接收。
修复步骤
1. 修正后端Cookie配置
修改main.py中response.set_cookie的参数,去掉Domain的协议前缀,也可以直接省略Domain参数(让浏览器自动匹配当前请求的域名):
response.set_cookie( key='access_token', value=access_token, httponly=True, domain='localhost', # 去掉协议前缀,或直接删除该行 path='/', # 本地开发环境无需设置secure,HTTPS生产环境需开启secure=True )
2. 更新Vite代理配置
在vite.config.ts的代理设置中添加withCredentials: true,确保代理时保留Cookie和认证头:
export default defineConfig({ plugins: [react()], server: { proxy: { '/api/*': { target: 'http://localhost:4242', changeOrigin: true, withCredentials: true, // 新增此行 }, }, }, });
3. 确认Fetch请求的Credentials配置
确保前端fetch请求中credentials参数设置正确,代理后的同域场景下same-origin或include均可:
fetch('/api/v1/token', { method: 'POST', credentials: 'include', // 或 'same-origin' // 其他请求参数(如FormData)... });
验证方法
修复后重启前后端服务,完成登录请求后:
- 打开浏览器开发者工具,在Application > Cookies > http://localhost:5173下查看是否存在
access_token - 检查响应头的
Set-Cookie字段,确认格式正确(无协议前缀,Domain为localhost或匹配当前域名)
内容的提问来源于stack exchange,提问作者pmo42
相关产品推荐
相关产品推荐

