관리 메뉴

Jun Hyuk Kim's Blog

[Backend] CORS 본문

Coding Explanation

[Backend] CORS

junhyuk1229 2023. 8. 6. 20:03

CORS or Cross-Origin Resource Sharing is an error we encountered when connecting the backend(fastapi) and the frontend(node.js). When connecting the two the following error happened

Access to fetch at 'URL_1' from origin 'URL_2' has been blocked by CORS policy

So I had to search about the CORS policy and here are the basic findings...


So what is CORS?

CORS is Cross-Origin Resource Sharing and is used to prevent other domain requests.

So if, for example, domain-a.com requests a HTTP request to domain-b.com it will be automatically blocked by CORS

CORS only allows, by default, same-origin access is allowed.


Why is CORS needed?

CORS is needed to prevent malicious or unwanted domains from accessing your domain and get important information from HTTP requests.


How to allow CORS in fastapi

CORS can be enabled using the middleware package in fastapi. The following code was used to solve my issues during the project.

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

# Add CORS to application / API
app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Of course allowing all origins, methods and headers are probably not a great practice.

  • allow_origins: domains
  • allow_methods: HTTP method ('PUT', 'GET', etc.)
  • allow_headers: HTML headers

Probably allow_origins needs to be changed to get better security but if the project is just a test / solo projects.


Used Sites

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

 

Cross-Origin Resource Sharing (CORS) - HTTP | MDN

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which

developer.mozilla.org

https://fastapi.tiangolo.com/tutorial/cors/

 

CORS (Cross-Origin Resource Sharing) - FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

https://medium.com/tribalscale/stop-cursing-cors-c2cbb4997057

 

Stop Cursing CORS

Most people doing frontend development at some point deal with CORS issues. The problem is that most people don’t know what is happening…

medium.com

https://hackernoon.com/understanding-cors-why-its-important-and-how-it-works

 

Understanding CORS: Why It's Important and How it Works | HackerNoon

This article will explain what CORS is, how it works, and why it is important.

hackernoon.com

'Coding Explanation' 카테고리의 다른 글

[SSH] Transfering files between servers  (0) 2023.08.07
About printing string formats in python  (0) 2023.03.08
About testing and printing  (0) 2022.12.20