요청과 응답

ClassBinu·2024년 4월 4일

Node.js 교과서

목록 보기
7/19

요청과 응답

통신은 기본적으로 클라이언트의 요청과 서버의 응답으로 이루어진다.
(서버는 또다른 서버에 대해 클라이언트가 될 수도 있음.)

이것도 요청도 일종의 이벤트다!

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  res.write("<h1>Hello World</h1>");
  res.end("Hello World");
});

server.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});

// server.on(이벤트, ...)로도 처리할 수 있음.

서버가 준비되었음을 알리는 로그를 출력하려면 listening 이벤트를 사용하고, 각각의 클라이언트 연결을 추적하거나 로그하고 싶다면 connection 이벤트를 사용합니다. 필요에 따라 두 이벤트를 모두 사용할 수도 있습니다.

요청에는 무조건 응답을 보내야 한다.
그렇지 않으면 클라이언트는 응답을 계속 기다리다가 타임아웃 처리한다.

html

코드를 다 쓰는게 아니라 html 파일을 읽어와서 res.end(data) 형식으로 응답한다.

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // index.html 파일의 경로를 구성
  const filePath = path.join(__dirname, 'index.html');
  
  // 파일을 읽어서 응답에 쓰기
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(500, { 'Content-Type': 'text/plain' });
      return res.end('Error loading index.html');
    }
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(data);
  });
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

라우팅

req.method의 메서드에 따라 다른 처리를 함.
메서드를 파악하고, 주소를 파싱해서 처리함.

req, res는 내부적으로 스트림으로 되어 있음.
그래서 데이터가 스트림 형식으로 전달됨.
문자열을 json으로 변환해야 함.

0개의 댓글