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

Axios携带浏览器Cookie发送POST请求时后端获取到空Cookie的问题求助

Axios携带浏览器Cookie发送POST请求时后端获取到空Cookie的问题求助

大家好,我遇到了一个关于Axios携带Cookie发送请求的问题,想请大家帮忙排查下:

我尝试用Axios向服务器发送POST请求,希望自动带上浏览器中保存的Cookie(登录请求/login的响应里已经成功设置了refresh token的Cookie),但后端接收到的Cookie对象却是空的。

我的Axios请求代码:

axios.post("http://127.0.0.1:8000/users/refresh", 
           {},
           {    
              withCredentials: true,
           })

后端的CORS配置(FastAPI):

origins = [
    "http://localhost:3000", // 重复配置是因为有时候Origin会在127.0.0.1和localhost之间切换
    "http://127.0.0.1:3000",
    "http://localhost:8080",
    "http://127.0.0.1:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

登录接口设置Cookie的代码:

@router.post("/login")
async def auth_user(
    response: JSONResponse,
    request: Request,
    uow: IUnitOfWork = UOWDep,
):
    data = await request.json()
    check = await authenticate_user(uow, data['login'], data['password'])
    if check is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail='Wrong login or/and password')

    access_token = create_access_token({"sub": str(check.id)})
    refresh_token = create_refresh_token({"sub": str(check.id)})

    response.set_cookie(key="user_refresh_token", value=refresh_token, secure=True, httponly=True)

    return {'access_token': access_token, 'user': {'login': check.login, 'is_admin': check.is_admin}}

刷新接口读取Cookie的代码(此处获取到的Cookie为空):

@router.post("/refresh")
async def refresh_access_token(
    response: Response,
    user_refresh_token=Cookie(default=None),
    user_data: UsersSchemeGet=Depends(get_current_user_refresh),
):
    access_token = create_access_token({"sub": str(user_data.id)})

    response.set_cookie(key="user_refresh_token", value=user_refresh_token, secure=True, httponly=True)
    return {'access_token': access_token, 'user': {'login': user_data.login, 'is_admin': user_data.is_admin}}

测试情况:

  • 用Postman发送请求时,一切正常,后端能正确获取到Cookie;
  • 浏览器开发者工具中可以看到登录响应后已成功保存Cookie:Cookie的key为user_refresh_token,对应有值,Domain为127.0.0.1,Path为/,且Secure和HttpOnly属性都已勾选。

备注:内容来源于stack exchange,提问作者ecler eclerchigov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:19:33