CORS (Cross-Origin Resource Sharing)은 http 프로토콜 헤더 중 하나로 서버가 자신 이외의 출처를 가지는 소스를 포함할 경우 이를 표시하는 기능을 합니다.
목적은 브라우저가 데이터 요청하고 서버가 요청받은 데이터를 전송 시 보안성을 향상하기 위함인데요.
설정에 따라 브라우저는 출처에 따라 접근을 제한하는데요. 예를 들어, Fetch API는 애플리케이션과 같은 출처를 가진 소스만 사용할 수 있습니다. 즉, domainA라는 도메인을 명을 가진 브라우저가 domainB라는 서버에 데이터를 요청하는 경우 헤더설정 여부에 따라 아래와 같이 접근이 제한되게 됩니다.
이런 문제는 프로덕션 버전에서는 발생하지 않고 개발환경에서만 발생하는데요. 이유는 브라우저가 스크립트에서 발생한 cross-origin HTTP요청을 제한하기 때문입니다. 아래와 같은 방법으로 해결할 수 있습니다.
1. proxy를 사용하여 도메인명을 변경하는 방법
2. CORS 헤더를 추가하는 방법
Node.js
CORS 헤더를 추가하는 방법
헤더는 서버 스크립트에 아래와 같이 추가합니다.
res.setHeader("Access-Control-Allow-Origin", "*")
두 번째 매개변수에 접근을 허용할 url을 입력하는데요. *은 모든 url을 허용합니다.
app.js
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested_With, Content-Type, Accept")
res.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, PATCH")
next()
})
다른 방법으로 npm의 cors 패키지를 사용하여 설정하는 것도 가능합니다.
In the command line
npm i cors
app.js
const express = require('express');
const app = express();
const cors = require("cors");
app.use(cors());
cors npm
cors
Node.js CORS middleware. Latest version: 2.8.5, last published: 4 years ago. Start using cors in your project by running `npm i cors`. There are 11660 other projects in the npm registry using cors.
www.npmjs.com
Firebase storage cors
참고
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://fetch.spec.whatwg.org/#http-cors-protocol
Fetch Standard
fetch.spec.whatwg.org
https://web.dev/same-site-same-origin/?utm_source=devtools
"동일 사이트" 및 "동일 출처" 이해하기
"동일 사이트"와 "동일 출처"는 자주 인용되지만 종종 오해됩니다. 이 기사는 이 둘이 무엇이며 어떻게 다른지 이해하는 데 도움이 됩니다.
web.dev
How to fix Firebase storage CORS issues in Angular and other frontend frameworks - Edupala
How to fix Firebase storage CORS issues in Angular and other frontend frameworks - Edupala
As for front-end developers, we often faced issues with CORS (Cross-origin resource sharing), I had faced Firebase storage CORS issues in one of my Angular
edupala.com
Cross-origin resource sharing (CORS) | Cloud Storage | Google Cloud
교차 출처 리소스 공유(CORS) | Cloud Storage | Google Cloud
의견 보내기 교차 출처 리소스 공유(CORS) 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 예시로 이동 동일 출처 정책은 서로 다른 출처의 리소스 간 상호작
cloud.google.com
'웹 개발 알아두기 > 네트워크' 카테고리의 다른 글
브라우저 (0) | 2023.01.08 |
---|---|
HTTP vs HTTPS (0) | 2022.12.29 |
캐시 (cache) (0) | 2022.12.23 |
네트워크 프락시 (Network Proxy) (0) | 2022.12.23 |
서비스 워커 (Service Worker) (0) | 2022.12.22 |