Programming/javascript
[NodeJS] hello world!
고양이의시간
2020. 6. 8. 00:16
NodeJS 에서 로컬서버 열어 통신해 보기
/**
*
* nodeJS 시작하기
* https://nodejs.org/ko/docs/guides/getting-started-guide/
*
*
* 터미널 명령어
* curl -X GET 'localhost:3000' // 서버에 요청을 보냄
*/
// http 모듈을 가져옴
const http = require('http');
// 호스트 네임: 서버의 주소
const hostname = '127.0.0.1';
// 클라이언트와 통신할 포트 설정
const port = 3000;
// req: request 객체(사용자 요청 정보를 담음)
// res: response 객체
const server = http.createServer((req, res) => {
// 사용자의 요청 url 을 확인
console.log(req.url);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// 클라이언트에게 문자열을 전송
res.end('Hello World\n');
});
// listen 서버를 클라이언트 요청을 받을 수 있도록, 대기 상태로 만듬
// params : (포트번호, 서버주소, 콜백함수)
server.listen(port, hostname, () => {
// listen 함수 호출이 완료되면, 메시지를 출력한다
console.log(`Server running at http://${hostname}:${port}/`);
});
클라이언트 GET 방식 요청으로 응답 확인
$ curl -X GET 'localhost:3000'