Reputation: 55
I use FastAPI to deploy an API on local server, using docker, something like this: http://192.168.1.33:8090/myAPI I already set allow CORS like this:
app = FastAPI()
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Calling from inside the network, it works fine.
When I map domain from outside to my API: https://example.com/myAPI
then the CORS error happens.
Access to fetch at 'https://example.com/myAPI' from origin 'https://example2.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I also tried to change origins
in above code to origins = ["https://example2.com"]
but it not work.
I know some people facing a similar question here: CORS issues when running a dockerised FastAPI application but he runs his docker in k8s.
What am I missing? Thanks
Upvotes: 1
Views: 6400
Reputation: 11
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"])
working for me
Upvotes: 0
Reputation: 31
I just added expose_headers=["*"]
in CORSMiddleware and it worked fine for me:
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"])
Also I don't recommend using "*" in origins. I solved tons of errors just by changing it.
Upvotes: 2