Network

node.js http 모듈을 이용해 웹 서버 만들기

mellomello.made 2022. 6. 17. 23:30

 

Node.js는 HTTP 요청을 보내거나, 응답을 받을 수 있는 도구들을 제공합니다.
HTTP 요청을 처리하고 응답을 보내 주는 프로그램을 웹 서버(Web Server)라고 부릅니다.

 

HTTP 모듈

HTTP 요청과 응답을 다루기 위해 HTTP 모듈을 사용한다. 웹서버를 구동하기 위한 기본적인 웹 모듈이다.

 

  • 서버 생성
모든 node 웹 서버 애플리케이션은 웹 서버 객체를 만들어야 한다. 이 때 createServer를 이용한다.
이 서버로 오는 HTTP 요청마다 createServer에 전달된 함수가 한 번씩 호출된다.
HTTP 요청이 서버에 오면 node가 트랜잭션을 다루려고 request와 response 객체를 전달하며 요청 핸들러 함수를 호출한다.

  1. 모듈을 사용하기 위해 http 모듈을 require로 불러온다.
  2. createServer()를 이용해 웹 서버 객체를 만든다.

 


 

 

  • request / response 객체
request는 클라이언트가 서버로 요청한 정보가 담기고, reponse에는 서버가 클라이언트에 응답한 내용이 담긴다.

📌 request 객체는 클라이언트가 서버로 요청할 때 보낸 정보가 담겨있어 요청이 있을 때마다 발생한다. 

  • request.method
  • request.url
  • request.header

 

스트림의 'data'와 'end' 이벤트에 이벤트 리스너를 등록해서 데이터를 받을 수 있다.
각 'data' 이벤트에서 발생시킨 청크는 Buffer이다. 이 청크가 문자열 데이터라는것을 알고 있다면 이 데이터를 배열에 수집한 다음 'end' 이벤트에서 이어 붙인 다음 문자열로 만드는 것이 가장 좋다.

 

nodeEventTarget.on(type, listener[, options]) // .on 이벤트 등록

 

 

📌 response 객체는 응답 상태 코드나 헤더 설정을 해줄 수 있고, 응답 데이터를 보낼 수 있다.

  • response.statusCode(상태코드): 상태코드 설정
  • response.setHeader('Content-Type','application/json'): 응답 헤더 설정
  • response.writeHead(상태코드,헤더): 상태코드와 헤더를 같이 설정
  • response.end(보낼 데이터): 보낼 데이터를 body에 담아 전달. end 메서드를 쓰기 전 상태코드와 헤더가 설정되어 있어야한다.

 

response.statusCode

암시적 헤더를 사용할 때(명시적으로 response.writeHead()를 호출하지 않음) 이 속성은 헤더가 플러시될 때 클라이언트에 전송될 상태 코드를 제어한다. 응답 헤더가 클라이언트로 전송된 후 이 속성은 전송된 상태 코드를 나타낸다.

response.statusCode = 404;

 

response.writeHead(statusCode[, statusMessage][, headers])

이 메서드는 메시지에서 한 번만 호출되어야 하며 response.end()가 호출되기 전에 호출되어야 한다.

 


 

<대문자/소문자 전환 POST 요청을 받을 때 요청에 맞는 응답을하는 서버>

const http = require('http');
const { url } = require("inspector");

const PORT = 4999;

const ip = "localhost";

//request : <http.들어오는 메시지> response: <http.서버 응답>
const server = http.createServer((request, response) => {
  console.log(
    `http request method is ${request.method}, url is ${request.url}`
  );
  response.writeHead(200, defaultCorsHeader);
  response.end('hello mini-server sprints');
  //Preflight가 OPTIONS이고 CORS 설정을 돌려줘야한다.
  if (request.method === "OPTIONS") {
    console.log(
      `http request method is ${request.method}, url is ${request.url}`
    );
    response.writeHead(200, defaultCorsHeader); //딱 한번만 쓸 수 있고 response.end가 쓰이기 전에만 쓸 수 있다.
    response.end(); //write함과 동시에 response를 종료하는 메소드. 종료하는 순간 클라이언트로 전송된다.
    return;
  }
  //메소드가 POST고, URL이 /UPPER이면 대문자로 응답을 돌려준다
  if (request.method === "POST" && request.url === "/upper") {
    let body = [];
    request
      .on("data", (chunk) => {
        //요청에 data가 있을 경우 처리하는 부분
        body.push(chunk);
      })
      .on("end", () => {
        //data처리가 다 끝났음을 알려주는 부분
        body = Buffer.concat(body).toString();
        console.log(
          `http request method is ${request.method}, url is ${request.url}`
        );
        // 여기서 `body`에 전체 요청 바디가 문자열로 담겨있습니다.
        //요청이 끝났으니 이제 응답을 해준다.
        response.writeHead(200, defaultCorsHeader);
        response.end(body.toUpperCase()); //정보 탑재 후 브라우저로 전송
      });
    return;
  }

  //메소드가 POST고, URL이 /LOWER이면 소문자로 응답을 돌려준다
  else if (request.method === "POST" && request.url === "/lower") {
    let body = [];
    request
      .on("data", (chunk) => {
        body.push(chunk);
      })
      .on("end", () => {
        body = Buffer.concat(body).toString();
        console.log(
          `http request method is ${request.method}, url is ${request.url}`
        );
        // 여기서 `body`에 전체 요청 바디가 문자열로 담겨있습니다.
        response.writeHead(200, defaultCorsHeader);
        response.end(body.toLowerCase()); //정보 탑재 후 브라우저로 전송
      });
    return;
  } else {
    response.statusCode = 404; //실패 상태 코드
    response.end();
  }
});

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

 

 

 

HTTP | Node.js v18.4.0 Documentation

HTTP# Source Code: lib/http.js To use the HTTP server and client one must require('node:http'). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possi

nodejs.org

https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/

'Network' 카테고리의 다른 글

Postman Message States 요청  (0) 2022.06.13
네트워크 REST API  (0) 2022.06.10