CORSMiddleware not work #7319
-
Hi, "http://127.0.0.1:8086/api" and "http://www.example.com" are in same pc. from fastapi import FastAPI app = FastAPI() |
Beta Was this translation helpful? Give feedback.
Replies: 104 comments 10 replies
-
How do you make the request? Could you use the web devtools to see how the request look like (with HTTP headers)? Also you may want to follow the issue template. |
Beta Was this translation helpful? Give feedback.
-
var apiUrl = "http://127.0.0.1:8086/api"; Client: Response: |
Beta Was this translation helpful? Give feedback.
-
You should add app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
) |
Beta Was this translation helpful? Give feedback.
-
Please note that Safari does not support the wildcard |
Beta Was this translation helpful? Give feedback.
-
I seem to be running into the same issue: app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"])
@app.post("/tokenize/", summary="Process batches of text", response_model=ResponseModel)
def tokenize(query: RequestModel):
# do stuff but after a POST request from my React front-end, console notifies me:
|
Beta Was this translation helpful? Give feedback.
-
@BramVanroy |
Beta Was this translation helpful? Give feedback.
-
@ScrimForever was it an |
Beta Was this translation helpful? Give feedback.
-
When i use fastapi CORSMiddleware, same as Bram, i receive error when use method POST, so, i change to starlette cors, and works. Just it. |
Beta Was this translation helpful? Give feedback.
-
That seems very strange, as fastapi doesn't have a cors implementation - it just exposes starlettes one See https://github.com/tiangolo/fastapi/blob/master/fastapi/middleware/cors.py |
Beta Was this translation helpful? Give feedback.
-
I have the same issue here. any updates, guys? |
Beta Was this translation helpful? Give feedback.
-
@tricosmo try importing from Starlette. from starlette.middleware.cors import CORSMiddleware |
Beta Was this translation helpful? Give feedback.
-
Thanks @ycd , that is what I have. Plus as @Mause mentioned about, it doesn't make sense. import logging
import uvicorn
from fastapi import APIRouter, Depends, FastAPI
from fastapi_aad_auth import AADAuth, AuthenticationState
from starlette.middleware.cors import CORSMiddleware
auth_provider = AADAuth()
logging.basicConfig(level="DEBUG")
router = APIRouter()
@router.get("/hello")
async def hello_world(
auth_state: AuthenticationState = Depends(auth_provider.api_auth_scheme),
):
print(auth_state)
return {"hello": "world"}
app = FastAPI(
title="fastapi_aad_auth test app",
description="Testapp for Adding Azure Active Directory Authentication for FastAPI",
openapi_url=f"/api/v1/openapi.json",
docs_url="/api/docs",
swagger_ui_init_oauth=auth_provider.api_auth_scheme.init_oauth,
redoc_url="/api/redoc",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8001", "http://0.0.0.0:8001"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(router)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", debug=True, port=8001, log_level="debug")
|
Beta Was this translation helpful? Give feedback.
-
@tricosmo I think you have misunderstood the purpose of cors - you can only configure requests to your website, not from |
Beta Was this translation helpful? Give feedback.
-
@Mause Thanks, that is a bit of silly me. |
Beta Was this translation helpful? Give feedback.
-
My solution was to move my |
Beta Was this translation helpful? Give feedback.
-
I managed to solve it after a lot of struggle hehe. Cors with fastapi, the url of the client that can access the end-point of the api must be declared and also in the response of each request it must be declared which client can receive the response. Unlike django, which has a setup that abstracts all this logic, making it necessary to declare the client's url only once. So I created a middleware to add the header in the requests responses.
|
Beta Was this translation helpful? Give feedback.
-
I found the issue! Try a solution from this answer https://stackoverflow.com/questions/69802274/getting-a-cors-error-even-after-adding-corsmiddleware/75699497#75699497 Solution 1) Tested by us. Go throw all your fastAPI routes. Remove every trailing slash. For example, we had this code
Change it to
Solution 2) We did not test it, but it should have the same effect. Install this module https://libraries.io/pypi/fastapi-lambda-router |
Beta Was this translation helpful? Give feedback.
-
I've got an issue where, despite specifying CORS requirements exactly as stated in the tutorial page the API processes the request and provides a valid response. Snapshot of the code:
If I make a request from a local file, or from a file hosted on another server / URL then the request succeeds when I expect it shouldn't. |
Beta Was this translation helpful? Give feedback.
-
I was using APIRouter() for routing , solution by @nefarioustim -#1663 (comment) worked for me. |
Beta Was this translation helpful? Give feedback.
-
The backend server should redirect, it should return 401 unauthorized and the client side (frontend) needs to redirect by himself. |
Beta Was this translation helpful? Give feedback.
-
Hi all, like this app = FastAPI() app.add_middleware( and added below way and many other ways but not working |
Beta Was this translation helpful? Give feedback.
-
The only way to solve it, at least for me was moving the
|
Beta Was this translation helpful? Give feedback.
-
I just want to notice, that runtime errors in endpoint will cause CORS error on front. So if you faced this - check logs on the server side. |
Beta Was this translation helpful? Give feedback.
-
In my case the problem was in '/' at the end of origin. |
Beta Was this translation helpful? Give feedback.
-
Summary of every single solution in all of these threads 😘Yes the struggle is still real in 2024 😒 😭 😭 🧨I have just spent the entire day on this, let me take you through all the steps I've tried/taken and "which delta" eventually made the shangabang work. TL/DRBefore you try anything, remove all trailing slashes, even in
MAGIQUE 🪄 🧙🏻♂️ ✅ IT WORKSThe changes that are currently present in my backend are:
But what the fudge is actually working then?
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(..,redirect_slashes=False)
app.include_router(best_router_known_to_mankind)
@app.get("/ping)"
async def healthcheck():
return "pong"
app.add_middleware(...) Still works.
|
Beta Was this translation helpful? Give feedback.
-
I also meet the cors error,It not present in my chrome network display cors error,It display my chrome console. |
Beta Was this translation helpful? Give feedback.
-
My case was specific to server side event. I finally notice that I must set withCredentials: true while making request on the client side.
|
Beta Was this translation helpful? Give feedback.
-
I have just figured out the problem.
The result is that only the The most important is, I find there is a small bug in my code of the API, but it only report CORS error on web instead of throwing error correctly on python log. |
Beta Was this translation helpful? Give feedback.
-
This discussion started in 2020 and this problem still happens. Is there any fix being worked on? Even Flask that has a poor documentation and "structure" have CORS easily set up. |
Beta Was this translation helpful? Give feedback.
-
WHILE DEBUGGING THIS, MAKE SURE YOUR UVICORN SERVER IS PROPERLY RESTARTED!!Wasted one whole day trying all the solutions to debug the issue lmao. The problem was a simple typo on my origins, but I thought it was not working because I still received the same error on my frontend. Turns out the server was not reloading, even though it seemed like it was from the log. I also thought I "killed" the process by closing the VS Code terminal window. Had to manually kill the task to reboot the server (guide) I've never felt so stupid lol. |
Beta Was this translation helpful? Give feedback.
My solution was to move my
app.add_middleware(CORSMiddleware, allow_origins=["*"])
to the bottom of all previousapp.
configuration. I'm usingfastapi_versioning
, and it seems to break middleware when placed after theCORSMiddleware
config.