」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 為什麼我的React前端不從FastApi後端接收cookie?

為什麼我的React前端不從FastApi後端接收cookie?

發佈於2025-03-25
瀏覽:509

Why Isn't My React Frontend Receiving Cookies from My FastAPI Backend?

FastAPI Cookie Not Received by React Frontend: Resolution

When using FastAPI as the backend and React as the frontend communicated via AJAX requests, cookies set by FastAPI might fail to be received by React. This inconsistent behavior can be attributed to the distinct port numbers used by both applications, which creates a cross-origin request scenario.

To address this issue, several steps are necessary:

  1. Set Cookies Correctly in FastAPI:
    Ensure that cookies are created and set in FastAPI without errors.驗證該響應是否包含一個“狀態”:“成功”,具有200個狀態代碼。
  2. 在React中啟用Cookie Concectance:

    在您的React應用程序中配置AXIOS請求,以通過將帶有Credentials屬性設置為TRUE來接收Cookie。這對於交叉原始請求是必要的,要求包括cookie等憑據。 }); 在fastapi中指定允許的啟動:由於請求的交叉孔子性質,因此您必須明確指定允許訪問API的起源。這包括您的React前端的域和端口。
    在corsmiddleware中允許憑證:

    在您的FastApi應用程序中,請確保Corsmiddleware配置為Allow_credentials設置為true。這將訪問控制的標題設置為true,從而允許憑據包含在交叉響應中。


    通過遵循以下步驟,FastApi應該成功地將cookie返回您的React FrontEnd。請記住要徹底檢查cookie是否正確設置了,沒有在Axios Post請求中返回錯誤。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3