This blog was last modified 468 days before.

During development of one of my project, which use React and FastAPI, we seemed to face with some CORS related issues, and this blog is actually serve as a dev note for myself about some CORS issue and corresponding solution.

API Server Cross Origin Config

Access-Control-Allow-Origin

We should add the frontend URL address into this header.

Notice that address consist of 3 different part:

  • Protocol
  • Host
  • Port (Alternative)

Which means, hosts like:

These are all different addresses and need to be added to header respectively (if you want to use these domains to send CORS request).

Allow-Credentials

In default cases, when sending CORS requests, operations like Cookies etc are forbidden. If you want to enable features like Cookies, you should add Allow-Credentials headers in HTTP response.

FastAPI CORS Middleware

One simple way to handle CORS request in FastAPI is using CORSMiddleware which is also the official recommended way. For more info, check FastAPI Official CORS Tutorial

There are code snippet in official guide:

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

However, there are cases in StackOverflow saying that this method may faced with some issues and may doesn't work in some occassion. Then here is another alt implementation of CORSMiddleware like below:

app = fastapi.FastAPI(
    # other params
    middleware=middlewares,
)

middlewares = [
    Middleware(
        CORSMiddleware,
        allow_origins=settings.BACKEND_CORS_ORIGINS,
        allow_credentials=settings.BACKEND_CORS_CREDENTIALS,
        allow_methods=settings.BACKEND_CORS_METHODS,
        allow_headers=settings.BACKEND_CORS_HEADERS,
    )
]

Notice that middlewares is a list which you can also add other middlewares.

CORS Error in frontned

Sometimes we may see CORS error in fronend console like below:

Actually this may not only means your config about CORS is wrong, but also can refers to some other bugs in backend APi.

For example in the example above, if we go to backend server and check console, we could find there actually an 500 internal server error thrown by backend.

image.png

But why frontend tells us there is a CORS error?

After checking, we infer that because of some reasons, the response actaully can't reach to the CORSMiddleware after the 500 internal error has been thrown and cause frontend to report CORS error.

Links & Refs

CORS - MDN Web Docs

CORS Tutorial - FastAPI Docs