𝗠𝘆 𝗙𝗶𝗿𝘀𝘁 𝗖𝗢𝗥𝗦 𝗘𝗿𝗿𝗼𝗿 𝗜𝗻 𝗙𝗮𝘀𝘁𝗔𝗣𝗜
I learn by building. I built an expense tracker. I used FastAPI for the backend. I used HTML and JavaScript for the frontend.
The server started. Swagger UI worked. The HTML page failed. The Load Expenses button did nothing.
I checked my Python code. I checked my fetch request. Nothing looked wrong.
I opened the browser console. I saw a red error. CORS blocked the request.
The frontend used port 3000. The backend used port 8000. The browser saw different origins. It blocked the connection.
I added CORSMiddleware to my FastAPI code. I allowed the origin http://127.0.0.1:3000. The error vanished.
Lessons for you:
- Open your browser console first.
- Test your API separately.
- CORS errors happen in the browser. They are not code bugs.
Source: https://dev.to/bynilotpal/my-first-cors-error-in-fastapi-2hf6