<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module" src="./dist/hello.js"></script>
</body>
</html>
다음 html파일을 로컬환경에서 크롬브라우저로 실행 시켰더니
Access to script at 'file:///경로/hello.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https, isolated-app.
이와 같은 에러메시지가 발생했습니다.
1. 발생원인
<script type=module>의 특성
먼저 MDN의 javascript modules에 관한 설명에 따르면 문제가 된 부분같이 type을 module로 설정한<script> 태그가 포함된 HTML 파일을 로컬에서 로드할 경우 자바스크립트 모듈 보안 요구사항으로 인해 CORS 오류가 발생한다고 합니다.
때문에 ajax로 요청한 것임 아님에도 불구하고 CORS 오류가 발생했던 것이죠.
로컬의 리소스를 요청할 때의 origin(출처)은 null
에러코드에서 알 수 있듯 출처가 null로 넘어온 script에 대한 접근이 CORS정책에 따라 제한되었다고 나와있습니다.
즉, 잘못된 리소스를 요청한 것이 되어 CORS에러가 발생했던 것입니다.
2. 해결방법
먼저 터미널을 엽니다.
http-server가 없다면
npm install http-server -g
위 키워드로 http-server를 전역으로 설치한 다음
npx http-server
위 명령어로 http-server를 실행시켜 해당 폴더를 서버에 올립니다.
http://127.0.0.1:8080
위 URL로 접속해서 에러가 사라진것을 확인할수 있습니다.
만약 서버가 올라가는 포트를 8080이 아닌 다른 포트로 실행하고 싶다면
npx http-server -p 원하는 포트번호
로 서버를 실행해 해당 포트로 접속하면 됩니다.