[Web Server] Building server using Node.js

Steve·2021년 5월 29일
0

웹개발 코스

목록 보기
34/59

유용한 서버 개발 툴

Nodemon

서버용 js 파일을 수정하면 ctrl c 로 서버를 끄고 node filename.js 로 다시 실행해야지만 수정한 내용이 반영이 되는데, nodemon은 수정이 일어날 시 이 과정을 알아서 해준다.

Debugging

  • --inspect : 크롬 디버거에 node.js 디버거 추가
  • -brk : 아예 처음부터 break 걸기

package.json 파일의 script 에 start 를 추가

  • start: nodemon --inspect filename.js

디버깅 관련 node.js doc

https://nodejs.org/dist/latest-v14.x/docs/api/debugger.html#debugger_advanced_usage

Creating node.js server

노드 공식 문서 Anatomy of an HTTP Transaction
https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/

공식 문서의 예시 convention 기준.

 // http 모듈을 불러온다.
const http = require('http');

// port, ip 정의
const PORT = 5000; // 내가 원하는 포트로. (front 서버는 주로 3000, node.js 81, mvc 88)
const ip = 'localhost';

// 서버를 만든다.
const server = http.createServer((request, response)=> {
  // 메소드와 url에 따라 분기된다.
  // CORS 요청의 메소드는 "OPTIONS" 이다.
  if (request.method === "OPTIONS"){ 
    // Sends a response header to the request.
    response.writeHead(200, defaultCorsHeader);
    // Finishes sending the request.
    response.end();
  }
  
  else if (request.method === "GET"){
    //...
  }
  
  else if (request.method === "POST"){
    // node.js guide 에서 제시한 방식
    let body = [];
      request.on('data', (chunk) => {
        body.push(chunk);
      }).on('end', () => {
      body = Buffer.concat(body).toString();
    });
    
    // 좀 더 간단한 방식
    let body = '';
    if (request.url === '/someword') {
      // 보낸 body 를 가져온다.
      request.on('data', chunk => {
        body += chunk;
      })
      // 작업을 한 후 응답한다.
      request.on('end', () => {
        //...
        response.writeHead(201, defaultCorsHeader);
        response.end(body);
      })   
    }
  }
  
  //에러처리
  else {
    response.writeHead(404, defaultCorsHeader);
    response.end("404 NOT FOUND");
  }
  
}.listen(5000)

/* listen 함수는 http 서버를 시작하게 되며 
 * 인자로 전달되는 포트의 요청을 받도록 대기시킨다. 
 * 위처럼 붙여서 연결해도 되고 따로 빼서 작성해도 된다. */
server.listen(PORT, ip, ()=>{
  console.log(`http server listen on ${ip}:${PORT}`)
})
// 만약 .listen 함수를 쓰지 않으면 에러가 뜬다.
// Failed to load resource: net::ERR_CONNECTION_REFUSED

// CORS 요청을 받기 위한 헤더
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
}               
  • response.writeHead(statusCode[, statusMessage][, headers])
  • response.end([data[, encoding]][, callback])
    This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

서버 구현의 단계

1단계 : 요청 메소드 정리
2단계 : route 정리
3단계 : 요청 데이터 받기
4단계 : 구현
5단계 : 데이터 + 상태 응답

profile
게임과 프론트엔드에 관심이 많습니다.

0개의 댓글