4

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"}

Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85
Mohammad FaRis
  • 63
  • 1
  • 3
  • 4

4 Answers4

11

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

DollarAkshay
  • 2,063
  • 1
  • 21
  • 39
Sam_Ste
  • 334
  • 2
  • 16
6

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.

Herc53
  • 61
  • 1
  • 3
3

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
1

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
Bhavesh Achhada
  • 101
  • 1
  • 9