1. Express 도입

초반에 했었던, 서버 작성파일을 가져와서 분석해보자.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0555cc9e-3eb1-486f-9b02-d1fd37f4e1e0/Untitled.png

const http = require('http');
// http 모듈을 사용하기 위해서 require 로 가져오고, http 변수에 담는다.

const hostname = '127.0.0.1';
// IP 는, 어떤 컴퓨터를 식별하는 식별자이다.
// 127.0.0.1 IP 를 통해서 들어온 사용자만 서버로 보내준다.
const port = 3000;
// 컴퓨터에 설치된 여러 서버들 중에서 나는 3000번 포트를 웹 서버로사용하겠다.

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});
// http 모듈에 있는 createServer 함수를 호출한다.
// 이를 server 변수에 담는다.
// 두 개의 인자를 받는데, req 인자는 요청과 관련된 것이고, res 인자는 응답과 관련된 객체이다.
// 요청한 사용자에게 응답할 것인가는, 두 번째 매개변수인 res 를 통해서 판단한다.

server.listen(port, hostname, () => {
  console.log(`Server running at <http://$>{hostname}:${port}/`);
});
// createServer 가 만든 서버를 listen 한다.
// listen 메서드는 콜백으로 비동기적으로 작동한다.

// 위에 작성된 코드를 익명함수로 사용함으로써, 축약한 형태이다.
var server = http.createServer(function(req, res){
	res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});
server.listen(port, hostname, function(){
	console.log(`Server running at <http://$>{hostname}:${port}/`);
});

이러한 방식은 굉장히 편하지만, 더 적은 코드로 더 많은 일들을 해줄 수 있는 프레임워크들이 존재한다.

노드를 직접 작성해서 웹을 만들면 좋겠지만, 이미 만들어진 프레임워크를 통해서 작성하는 것이 더 편하고 효율적이다.

여기에서는, Express 라는 웹 프레임워크를 활용함으로써, 웹 서버 개발을 다뤄볼 것이다.

2. Express 설치

Express - Node.js 웹 애플리케이션 프레임워크

내가 express 를 사용할 디렉터리로 이동해서 설치하거나, 없다면 디렉터리를 만들고, 설치한다.

$ mkdir myapp
$ cd myapp
$ npm init

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/d700d2db-6d4c-451b-8e1f-f311c71a54a3/Untitled.png

(package.json 파일에 'dependencies' 항목에 express 가 추가된 것을 확인할 수 있다.)

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/16263dd1-187f-4ebc-86b7-7942e63453bd/Untitled.png