Fastapi: [BUG] Unable to set CORS headers

Created on 3 Apr 2019  Â·  8Comments  Â·  Source: tiangolo/fastapi

Describe the bug

Attempting to add CORS headers does not work.

To Reproduce
There are two ways to add the CORS headers- using the Starlette CORS middleware, or by manually adding headers. Neither work.

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

app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=['*'])

@app.get('/ping', content_type=UJSONResponse)
def health_check():
    return UJSONResponse({'status': 'ok'}, headers={'Access-Control-Allow-Origin': '*'})

It looks like the middleware is just completely ignored, and the headers defined in the routes don't work when the "OPTIONS" verb is used.

Expected behavior
The CORS headers should be set.

Environment:

Tested with tiangolo/uvicorn-gunicorn-fastapi:python3.6.

bug

Most helpful comment

@CoderCharm, we ran into this issue a while back it is due to CORS policies: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

If the request sends credentials then you are not allowed any origin (i.e allow_origins=['*']) and the origin must be 'reflected' back by the Middleware dynamically (Which is what the regex does):

https://github.com/encode/starlette/blob/93878323e57e0bab92b4622849c67f5a7c96b24e/starlette/middleware/cors.py#L107

All 8 comments

My mistake- I was trying to POST but hadn't actually set that verb to allowed.

Thanks for reporting back that you were able to fix it.

Also, you can check the project generator section that handles that: https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app/main.py#L20-L26

@tiangolo - that's literally how I found my mistake! Having that starter app really helped out.

Aha! Hehe great.

A neat fix is also to ensure you have imported the response in the respective endpoint i.e
from starlette.responses import JSONResponse, Response, UJSONResponse

I have the same problem。

Environment

fastapi==0.55.1
python3.7

my code

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

GETrequests can cross domains, but POST requests cannot。

I saw that there was a allow_origin_regex way in the document, so I did it and solved my problem, GET and POST can be cross domain.

app.add_middleware(
    CORSMiddleware,
    # allow_origins=origins,
    allow_origin_regex='https?://.*',
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

I don't know why `allow_origins=['*'] 'will be invalid.

@CoderCharm, we ran into this issue a while back it is due to CORS policies: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

If the request sends credentials then you are not allowed any origin (i.e allow_origins=['*']) and the origin must be 'reflected' back by the Middleware dynamically (Which is what the regex does):

https://github.com/encode/starlette/blob/93878323e57e0bab92b4622849c67f5a7c96b24e/starlette/middleware/cors.py#L107

@ccharlesgb Thank you for answering my doubts.

Was this page helpful?
0 / 5 - 0 ratings