http.createServer

Creating the dots·2021년 8월 4일
0

Node js

목록 보기
1/3
post-thumbnail

이벤트 이해하기

//basic-server.js 
//http 서버가 있어야 웹 브라우저의 요청을 처리할 수 있기 때문에 http 모듈을 사용한다
const http = require('http');
const PORT = 5000;
const ip = 'localhost';

const server = http.createServer((req,res) => {
  //req 구조분해 할당 
  const {method, url} = req;
  
  //method가 OPTIONS인 경우 ===> CORS가 실행될때, 서버에 전달되는 preflight의 메소드
  if(method === 'OPTIONS'){
    res.writeHead(200, defaultCorsHeader);
    response.end();
  }
  
  //method가 POST이고 url이 /upper인 경우
  if(method === 'POST && url === '/uppper'){
    let data = [];
     request
     .on('data', (chunk) => {
       data.push(chunk) })
     .on('end', () => {
       res.writeHead(201, defaultCorsHeader);
       res.end(Buffer.concat(data).toString().toUpperCase());
     }
  }
  
  //method가 POST이고 url이 /lower인 경우
  if(method === 'POST' && url === '/lower'){
       let data = [];
       request
       .on('data', (chunk) => {
         data.push(chunk) })
       .on('end', () => {
         res.writeHead(201, defaultCorsHeader);
         res.end(Buffer.concat(data).toString().toLowerCase())
     }
  }
  
  else{
        response.statusCode = 404;
        response.end();
 }
  
}

server.listen(PORT, ip, () => {
  console.log(`http server listen on ${ip}:${PORT}`);
});

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
};

  • on(이벤트명, 콜백)
    이벤트 이름과 이벤트가 발생했을때 작동할 콜백함수를 인자로 받는다. 이렇게 연결하는 동작을 이벤트 리스닝이라고 부른다. 하나의 이벤트에 여러개의 콜백을 실행시킬 수 있다.

  • on('data', 콜백)
    The 'data' event is emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer.
    스트림이 데이터 청크의 소유권을 소비자(consumer)에게 양도할때마다 'data'가 이벤트가 발생한다.

  • on('end', 콜백)
    The 'end' event is emitted when there is no more data to be consumed from the stream.
    스트림에서 더이상 사용할 데이터가 없을때 'end' 이벤트가 발생한다. 'end' 이벤트는 데이터가 모두 소비될때까지('data' 이벤트가 끝날때까지) 절대 실행되지 않는다.

//이벤트 생성하기
const EventEmitter = require('events');
const myEvent = new EventEmitter();

myEvent.addListener('introduce', () => {
  console.log('Hi,');
});
myEvent.on('introduce', () => {
  console.log('nice to meet you');
});
myEvent.emit('introduce'); // Hi, nice to meet you 
  • addListener(이벤트명, 콜백)
    on(이벤트명, 콜백)과 기능이 같다

  • emit(이벤트명)
    이벤트를 호출한다.

  • once(이벤트명, 콜백)
    여러분 호출해도 콜백이 한번만 실행된다.

  • listenerCount(이벤트명)
    현재 리스너가 몇 개 연결되어있는지 확인한다.

  • response.end([data[,encoding]],[,callback])
    이 메소드가 호출되면, 서버에게 response headers와 body가 모두 보내졌다는 것을 의미하며, 이 메소드는 매 응답마다 꼭 포함되어야 한다.

    • 데이터는 문자열 또는 Buffer
      데이터가 명시되어있으면 response.write(data, encoding)과 response.end(callback)을 쓴 것과 동일하게 기능한다.
    • encoding은 문자열
    • callback은 함수

추가

  • 모듈(module)
    특정한 기능을 하는 함수나 변수들의 집합으로 모듈을 만들어두면 여러 프로그램에서 모듈을 재사용할 수 있다. (자바스크립트에서 함수를 만들어 재사용하는 것과 같은 맥락)

  • nodemon 패키지
    소스코드가 바뀔때마다 노드를 재실행해주는 패키지

//pacakage.json에 nodemon 추가하기
npm install --save-dev nodemon

https://nodejs.org/api/
도서 Node.js 교과서 (길벗, 조현영 저)

profile
어제보다 나은 오늘을 만드는 중

0개의 댓글