Mohammad FaRis
Mohammad FaRis

Reputation: 113

FastAPI: CORS Middleware not working with GET method

I try to use CORS on the FastAPi framework but it dose not working with GET method

Here's the code I'm working on:


from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/test1")
async def test1():
    return {"message": "Hello World"}

Upvotes: 9

Views: 18269

Answers (4)

Herc53
Herc53

Reputation: 161

When testing, make sure you add Origin header to your request. Otherwise CORSMiddleware will not send back the cors headers.

It may not be clear at first, but it is written here in the documentation:

Simple requests

Any request with an Origin header. In this case the middleware will pass the request through as normal, but will include appropriate CORS headers on the response.

So any request without an Origin will be ignored by CORSMiddleware and no CORS headers will be added.

Upvotes: 16

Bhavesh Achhada
Bhavesh Achhada

Reputation: 323

For me, none of the above mentioned ideas worked. I had to create a custom middleware like this.

@app.middleware("http")
async def cors_handler(request: Request, call_next):
    response: Response = await call_next(request)
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Allow-Origin'] = os.environ.get('allowedOrigins')
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = '*'
    return response

Upvotes: 6

Sam_Ste
Sam_Ste

Reputation: 464

I had the same issue and the solution is to not use add_middelware but do the following:

First import from Starlette:

from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware

Create the middleware:

middleware = [
    Middleware(
        CORSMiddleware,
        allow_origins=['*'],
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*']
    )
]

and then:

app = FastAPI(middleware=middleware)

This should work

Upvotes: 20

user2209120
user2209120

Reputation: 71

Thanks @Sam_Ste, I had the same problem! I set my imports back to FastAPI and it still works. I think they are just proxies for the starlette modules (IMHO). The method is the vital thing, not using app_middleware.

from fastapi.middleware import Middleware
from fastapi.middleware.cors import CORSMiddleware

Upvotes: 4

Related Questions