DEV Community

Nilotpal Baishya
Nilotpal Baishya

Posted on

My First CORS Error in FastAPI

I'm learning FastAPI. And I am not a person who can learn by watching tutorials.

So I decided to learn while building. So I built something small just to start with FastAPI. A basic expense tracker.

Nothing fancy. Just a FastAPI backend with a few endpoints and a simple HTML page with JavaScript. There are three buttons in it: Load Expenses, Add Expense, Calculate Total. I just wanted to see how frontend talks to backend.

Everything seemed fine

I started the server. No errors. Tested my API in Swagger UI. Worked perfectly. Then I opened my HTML file. Clicked "Load Expenses."

But there was nothing. like no expenses, no error, just nothing.

I stared at the screen thinking What did I do wrong?

I blamed my backend first

I thought I messed up my Python code. I checked everything but there was nothing wrong. Then tested Swagger UI again. The endpoint was fine.

Then I blamed my frontend

So I went to check my fetch request. It looked fine to me. I checked the button. Worked fine. But after all this there was still nothing.

Then I opened the browser console

This was the moment. I clicked F12 and saw this red error:

Access to fetch at 'http://127.0.0.1:8000/expenses' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I had no idea what CORS meant.

What I learned

I learnt that my backend was working the whole time. I searched about CORS error and came to know about what is CORS and all. The browser was blocking it. SO my frontend was on port 3000 and my backend was on port 8000.They are different ports. The browser saw them as different "origins" and said "nope, not allowed unless the backend gives permission."
My backend wasn't giving permission. So I added the CORS middleware, it adds special HTTP headers to my backend responses.

The fix

I added this to my FastAPI code:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://127.0.0.1:3000"],
    allow_methods=["*"],
    allow_headers=["*"],
)
Enter fullscreen mode Exit fullscreen mode

What stuck with me

The fix was four lines. But what I actually learned was:

  1. I should always open the browser console FIRST. At least not after checking everything else.

  2. Test my API separately before blaming it.

  3. CORS errors are browser things, not code bugs.

Top comments (0)