Access to XMLHttpRequest X from origin Y 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.
I am running into CORS issues when trying to deploy an application to a cloud server.
- I managed to fix this problem when I was testing the application on my local machine (everything communicating via
localhost
) - I believe I also fixed the issue when I was using just ip addresses and the application was deployed to the cloud (can’t be totally certain about this – it was late last night when I was trying to deploy it)
- I now have a domain name, and I am now certainly having trouble with CORS
Archetecture
There is a server in the cloud which hosts the frontend and the backend of this system. The frontend is written using React+Vite, and is deployed as a static site using nginx on port 80.
The backend is written using Python+FastAPI, and is deployed inside a Docker container running on the same server. It exposes port 5555 for the API.
CORSMiddleware is enabled in FastAPI application:
from fastapi.middleware.cors import CORSMiddleware
origins = [
'http://localhost',
'http://localhost:80',
'http://localhost:5555',
'http://my-domain.co.uk',
'http://my-domain.co.uk:80',
'http://my-domain.co.uk:5555',
]
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
I am not totally sure which of these ports are required.
This is my understanding of how the CORS system works:
- The browser makes a request to the frontend at
my-domain.co.uk:80
. - Nginx returns the html, css and JS to the browser
- Some of the JS contains code to make an axios request to
my-domain.co.uk:5555/api/something
- The browser sees this as a cross origin request but makes the request anyway
- The backend server (FastAPI) receives the request to
my-domain.co.uk:5000/api/something
frommy-domain.co.uk:80
- (I guess the browser must send the information about which website originally gave it the javascript to make the next request?)
- I’m guessing the browser then needs to do the pre-flight check by sending something to the FastAPI backend, and that the FastAPI backend must reply with the CORS headers
- This doesn’t seem to be happening
- I would then guess if the browser did get back the CORS headers correctly, this would tell the browser that it is safe to make the full request to the backend to get the required data?
Have I understood the process by which CORS works correctly?
I have looked at some information in the “Network” tab of the developer tools in Chrome. I can’t find any headers which look like Access-Control-Allow-Origin
.
What might be causing these to be missing?