CORS (Cross-Origin Resource Sharing)
An origin is the combination of protocol (
https), domain (
localhost.tiangolo.com), and port (
So, all these are different origins:
Even if they are all in
localhost, they use different protocols or ports, so, they are different "origins".
So, let's say you have a frontend running in your browser at
http://localhost (because we don't specify a port, the browser will assume the default port
Then, the browser will send an HTTP
OPTIONS request to the backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (
To achieve this, the backend must have a list of "allowed origins".
In this case, it would have to include
http://localhost:8080 for the frontend to work correctly.
It's also possible to declare the list as
"*" (a "wildcard") to say that all are allowed.
But that will only allow certain types of communication, excluding everything that involves credentials: Cookies, Authorization headers like those used with Bearer Tokens, etc.
So, for everything to work correctly, it's better to specify explicitly the allowed origins.
You can configure it in your FastAPI application using Starlette's
- Import it from Starlette.
- Create a list of allowed origins (as strings).
- Add it as a "middleware" to your FastAPI application.
You can also specify if your backend allows:
- Credentials (Authorization headers, Cookies, etc).
- Specific HTTP methods (
PUT) or all of them with the wildcard
- Specific HTTP headers or all of them with the wildcard
from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
For more details of what you can specify in
CORSMiddleware, check Starlette's
For more info about CORS, check the Mozilla CORS documentation.