CORS understand Cross-Origin Resource Sharing mechanism

Hello developer. I know that it becomes a nightmare when front developer have issues with it. The async requests fails to fetch data from Back-end and a red message in console “…cors… cross-origin..”.

It’s harder to fix this issue when we don’t understand how navigator works when we try to fetch data from a REST Api.

What the hell is CORS ?

It is an HTTP-based mechanism that let front enf request data from backend but with different URL. For example, imagine running a PWA application in kaliex.co but this page requests data from api.kaliex.space. The two applications have different origin and that makes a CORS error.

How to fix that?

The browser will send an OPTION HTTP request to check that the request is safe to send. Then, the back end will send response header to the front application with Access-Control-Allow-Origin and Access-Control-Allow-Methods.

Each Web technology allows us to set up this values. You can put * to say that every front end application can request your backend application.

Let’s make a FastAPI example including CORS configs:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "https://kaliex.co",
    "https://localhost.kaliex.co",
    "http://localhost",
    "http://localhost:5000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def main():
    return {"message": "Hello World"}
Cross-Origin Resource Sharing
This schema can help you understanding CORS

Source:

You Might Also Like

Leave a Reply