본문 바로가기

Node.js

mini-node server

const http = require('http');//'http'모듈 가져오기.
//http모듈 : Node.js에서 웹 서버 만드는데 필요한 모듈

const PORT = 5000;
const ip = 'localhost';

const server = http.createServer((request, response) => {
//웹 서버객체를 만들어야한다 : http.createServer
// const {method, url} = request;
// 즉, method : HTTP method/동사 이고
// url: 전체 URI에서 프로토콜, 호스트, 포트를 제외한 것으로 'url-path부터 마지막 전부'

  if (request.method === 'OPTIONS') {
    response.writeHead(200, defaultCorsHeader);
    response.end();
  }


  if (request.method === 'POST' && request.url === '/upper') {
    let body = '';
    request.on('data', (chunk) => {
      body = body + chunk;
    })
//web browser가 POST방식으로 데이터 전송할 때,
//데이터가 엄청 많으면 데이터를 한번에 처리하다가는 프로그램이 꺼진다거나 컴퓨터에 무리가 갈 수 있다.
//그래서 Node.js에서는 POST방식으로 전송되는 데이터가 많을 경우를 대비해 조각조각의 양들을 서버쪽에서 수신할 때마다 콜백함수를 호출하도록 약속돼있다. 
//호출할 때, 'data'인자를 통해 수신한 정보를 주기로 약속.
//body에다가 callback이 실행될때마다 추가해주는 것. 

request.on('end', () => {
      body = body.toUpperCase();
      response.writeHead(200, defaultCorsHeader); 
 //writeHead메소드 : 헤더작성하는 메서드. 인자 : 상태코드, 헤더
      response.end(body);//body는 JSON형태인..듯하다...!
 // 응답 바디 전송.
 // 원래는 response.end(JSON.stringify(body))
    })
  //더이상 들어올 정보가 없으면 'end'뒤 콜백함수가 호출된다.
  //그말은 즉, 콜백함수가 실행됐을때는 정보수신이 끝났다고 생각하면 된다. 
    
  } else if (request.method === 'POST' && request.url === '/lower') {
    let body = '';
    request.on('data', (chunk) => {
      body = body + chunk;
      console.log(chunk);
      console.log(body);
    })
    request.on('end', () => {
      body = body.toLowerCase();
      response.writeHead(200, defaultCorsHeader); // 
      response.end(body); // body를 전송해주는것...?
    })
  } else {
    response.writeHead(404, defaultCorsHeader);
    //response 헤더에 'Access-Control-Allow-Origin': '*' 이것이 필요하기때문에
    //defaultCorsHeader가 들어감.
    response.end();
  }
})

server.listen(PORT, ip, () => {
  console.log(`http server listen on ${ip}:${PORT}`);
});
//listen메소드가 실행될때 비로소 웹서버가 실행되면서 PORT포트에 listen이 가게되고,
//그 listen이 성공하게 되면 뒤에 코드가 실행된다.

const defaultCorsHeader = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Accept',
  'Access-Control-Max-Age': 10
};