Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI: CORS Middleware not working with GET method

Tags:

fastapi

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

like image 403
Mohammad FaRis Avatar asked Mar 19 '26 00:03

Mohammad FaRis


2 Answers

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

like image 112
Sam_Ste Avatar answered Mar 26 '26 14:03

Sam_Ste


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.

like image 45
Herc53 Avatar answered Mar 26 '26 15:03

Herc53



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!