2. 노드로 만나는 Hello World

YoonJu Lee·2021년 7월 22일
0

이 장에서는 node의 http 모듈로 서버 구축한다.

우리는 마지막 코드를 보며..
Why using the Framework 'express'!!를 느껴야 한다.

1. Hello World 노드버전

노드의 헬로월드 코드 링크: https://nodejs.org/dist/latest-v6.x/docs/api/synopsis.html

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

curl

  • http 요청을 보낼수 있는 커맨드라인 명령어
curl -X GET 'localhost:3000'

2. 라우팅 추가하기

1. 어떤 경로로 접근해도 이 서버는 HelloWorld를 응답한다.

2. 사용자의 다양한 요청에 맞는 응답을 해 줘야 한다.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3001;

const server = http.createServer((req, res) => {

  // 사용자의 요청한 정보의 경로명에 맞게 분기한다. 
  // req : 사용자의 요청 정보 
  console.log(req.url);

  if (req.url === '/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n'); // end 함수로 client에게 hello world 보내줌.
  } else if (req.url === '/users') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('User list\n'); // end 함수로 client에게 hello world 보내줌.

  }
  else {
    res.statusCode = 404;
    res.end('Not Found')
  }


});

// listen함수 : 서버를 요청 대기상태로 만들어줌. (서버를 종료시키지 않고 계속 대기중.)
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

2번의 코드의 문제점..

node의 http 모듈로 서버 구축 ==> 코드가 길어지고 복잡해 짐에 따라 가독성이 떨어진다.
이로써, FrameWork인 'express'를 사용 할 것이다!!

profile
Coder가 아닌 Engineer를 향해서.

0개의 댓글