Node로 로컬 서버 실행하기
로컬에 있는 HTML 파일을 브라우저로 열면 file:///Users/gardenist/workspace/cmax-study/index.html
과 같이 http
가 아닌 file
프로토콜로 잡히고, github.com
과 같은 호스트를 표현할 수 없다. 이 경우 /ets/hosts
파일을 이용해 도메인을 부여한 것처럼 브라우저에 접근할 수 없는데,
단순 html
파일 작업이라면 무방하지만 Ajax 통신이 필요한 경우 서버에서 모든 Origin에 대해 Ajax를 허용(Allow)하지 않는 이상 테스트할 방법이 없다.
이를 위해 로컬의 파일을 localhost로 접속하기 위해 node
의 http-server
모듈을 활용한다.
$ npm install -g http-server
위와 같이 http-server
를 설치한 후 html 파일을 서빙할 디렉토리, 즉 html 파일이 위치한 곳으로 이동한 후 http-server
를 입력하여 실행해준 후 브라우저에서 localhost:8080
으로 접속한다.
$ cd <html파일이 있는 폴더>
$ http-server
(해당 폴더의 파일 목록이 표시되는 것을 확인할 수 있다. 아무런 필터링 없이 접근이 가능하므로 당연히 테스트 용으로만 사용해야 하고, 실 운영을 위해서 사용할 때는 보안 관련 설정이 추가되어야 한다.)
http-server --help
를 실행하면 실행 옵션에 대한 설명을 볼 수 있다.
usage: http-server [path] [options]
options:
-p Port to use [8080]
-a Address to use [0.0.0.0]
-d Show directory listings [true]
-i Display autoIndex [true]
-g --gzip Serve gzip files when possible [false]
-e --ext Default file extension if none supplied [none]
-s --silent Suppress log messages from output
--cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header
Optionally provide CORS headers list separated by commas
-o [path] Open browser window after starting the server
-c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
To disable caching, use -c-1.
-U --utc Use UTC time format in log messages.
-P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com
-S --ssl Enable https.
-C --cert Path to ssl cert file (default: cert.pem).
-K --key Path to ssl key file (default: key.pem).
-r --robots Respond to /robots.txt [User-agent: *\nDisallow: /]
--no-dotfiles Do not show dotfiles
-h --help Print this list and exit.
기본 포트는 8080 포트지만, -p
옵션을 줘서 http-server -p 4000
과 같이 입력하면 localhost:4000
으로 접속할 수 있다.