본문 바로가기

Web/HTML, CSS, Javascript

Javascript module 타입의 cors 문제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
    <script type="module" src="js/main.js"></script>
</body>
</html>

이렇게 module타입으로 js import를 하게되면, cors에러가 뜨게 됩니다.

file:///~~ 요런 url이 cors에 의해 block 되었다는 것인데요..ㅠ

npm으로 매우 간단하게 해결할 수 있습니다.

http-server를 활용하는 것입니다.

  1. npm install http-server -g
  1. index.html이 있는 경로에서 npx http-server 실행
  1. http://127.0.0.1:8080 에 접속! (포트 바꾸고 싶다면 npx http-server -p 포트번호)

끝!

조금 더 편하게 하고자 한다면 package.json에 script를 등록하면 됩니다.

"scripts": {
    ...,
    "start": "npx http-server -p 8000"
},