0

I have tried setting up the CORS headers as per the official docs.

But when I test the endpoint locally, the CORS headers don't appear.

from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import requests
from fastapi import Response
import os


load_dotenv()

key = os.environ["DRF_API_KEY"]

app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost:8000",
    "http://localhost:8080",
    "http://localhost:8080",
    "http://127.0.0.1:8000"
]


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

@app.get("/{email}")
async def root(email):
    print("hiya")
    # print("Email is ", email)
    # print("Key is ", key)
    r = requests.get(f'https://api.mydomain.io/retrieve_artist_user/{email}', headers={'Authorization': f'Api-Key {key}'})
    text = r.text
    print(text)
    return Response(content=text, media_type="application/json")

I am testing with Postman and keeping an eye on the Headers tab

1 Answers1

0

The CORS headers are not appearing because you are requesting the endpoint directly, not in a cross-origin context.

According to the FastAPI documentation :

The middleware responds to two particular types of HTTP request...

  • CORS preflight requests
  • Simple requests

So you have two ways to test if CORS headers are working correctly:

Use CORS preflight requests

These requests are typically made by your browser when making cross-origin requests. You can use a simple HTML page with the following script :

<script>
    fetch("http://localhost:8000/test").then((Response) => {
        return Response.json()
    }).then((data) => {
        console.log(data);
    })
</script>

This is suggested in this answer. You should see a CORS error in your browser's console because the browser has no known Origin and will use null as Origin. The CORS error should disappear should you allow all origins in your middleware :

origins = ["*"]

Use a simple request with an Origin header

Add an Origin header to your postman request. If this origin matches one allowed in your middleware, you should see an access-control-allow-origin header in the response.

TL;DR

CORS errors are caused by your browser refusing to share an API response with an origin, not by an API refusing to respond (check out https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

bastienlc
  • 53
  • 5