index.html 파일
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
<script type="module" src="./HTML_Project/javaScript/firebase.js"></script>
</html>
script에 type="module"을 사용하면, 브라우저는 이 스크립트를 일반 스크립트가 아니라 ES 모듈로 처리해.
firebase.js 파일
// Firebase SDK 라이브러리 가져오기
import { initializeApp } from "...";
import { getFirestore } from "...";
import { collection, addDoc } from "...";
import { getDocs } from "...";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "....",
authDomain: "....",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
...
이 HTML 파일을 브라우저에로 작동시키면 다음과 같은 CORS 오류가 뜬다.
CORS(Cross-Origin-Resource-Sharing) : 관련된 보안 기능 때문에 발생하는 오류이다. 웹 브라우저는 보안상 이유로, 현재 페이지가 로드된 도메인(orgin)과 다른 도메인(origin)에서 리소스를 요청할 경우, 그 요청을 제한하거나 차단하기 때문에 발생한다.
🔒 쉽게 설명하면
다른 출처에서 온 리소스를 브라우저가 가져올 수 있는지를 결정하는 보안 규칙이다.
🔍 상황 설명
1. index.html 파일을 브라우저로 열면, 주소가 다음과 같다.
file:///.../index.html
2. 이 HTML에서 자바스크립트 파일을 다음과 같이 불러온다.
<script type="module" src=".~~~/firebase.js"></script>
3. 이 경우에는 외부 JS 파일을 모듈로 로드하고 있다. 모듈로 스크립트를 불러오면 브라우저는 CORS 정책을 적용한다. 그 외부 리소스(JS 파일)에서 CORS 허용 헤더(Access-Control-Allow-Origin)가 없거나 잘못 설정되어 있다면, CORS 오류가 발생한다.
(module script는 CORS를 따라야 한다는 브라우저 규칙이 있다.)
해결 방법
1. script를 직접 ES 모듈 안에서 작성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
<script type="module">
// Firebase SDK 라이브러리 가져오기
import { initializeApp } from "...";
import { getFirestore } from "...";
import { collection, addDoc } from "...";
import { getDocs } from "...";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "....",
authDomain: "....",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
...
</script>
</html>
이렇게 사용하면, 브라우저가 외부에서 파일을 로드할 필요가 없어서 CORS 정책이 적용되지 않는다.
firebase에서 import한 것들은 외부 경로에 대한 CORS 정책이 적용되지만, Firebase의 경우 CORS 설정이 잘되어 있어 정상적으로 동작한다.(CORS 허용한 경우에는 괜찮다.)
2. 로컬 서버를 사용하는 방법이 있다.
다음 링크에서는 VSC에서 로컬 서버를 사용하는 방법이다.
'웹 기초' 카테고리의 다른 글
[Visual Studio Code Extensions] Live Server란? (0) | 2025.04.10 |
---|---|
[Vanila JavaScript] 파티클 만들기 (0) | 2025.04.09 |
[내일 배움 캠프, 웹 기초] html, <script> 태그의 위치 (0) | 2025.03.31 |
[내일 배움 캠프, 웹 기초] URL이란? (0) | 2025.03.31 |
[내일 배움 캠프, 웹 기초] index.html이란? (0) | 2025.03.28 |