순수 node.js로 간단한 서버 만들기

citron03·2022년 1월 29일
0

html, css, js

목록 보기
19/43

서버 생성

const http = require('http');

const server = http.createServer((request, response) => {
  // 여기서 작업이 진행됩니다!
});

또는 

const server = http.createServer();
server.on('request', (request, response) => {
  // 여기서 작업이 진행됩니다!
});
  • 위와 같이 http.createServer를 통해서 웹 서버 객체를 만들 수 있습니다.

  • createServer에 서버에서 일어날 활동을 작성합니다.

  • request 객체 내부에는 headers, method, url등이 들어있습니다.

  • method와 url을 보고 각 메소드에 맞는 응답을 할 수 있습니다.

Request body

  • POST나 PUT 메소드 request의 body에는 클라이언트에서 전송된 데이터가 들어와 있습니다.
let body = [];
request.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // 여기서 `body`에 전체 요청 바디가 문자열로 담겨있습니다.
});
  • 'data'와 'end' 이벤트에 이벤트 리스너를 등록해서 데이터를 받을 수 있습니다.

  • 받은 데이터는 body에 저장되며, end에서 데이터를 처리하여 reponse에 담아 보낼 수 있다.

오류

request.on('error', (err) => {
  // 여기서 `stderr`에 오류 메시지와 스택 트레이스를 출력합니다.
  console.error(err.stack);
});
  • 오류가 발생하면, 'error' 이벤트 리스너를 통해서 에러 메세지를 출력하고 에러 상황을 관리한다.

Response 하기

  • 응답을 하기위해서 reponse의 상태코드를 지정할 수 있다.
response.statusCode = 404; // 클라이언트에게 리소스를 찾을 수 없다고 알려줍니다.

or

response.statusCode = 200; // 정상 작동

or

response.statusCode = 201; // 새로운 리소스가 생성되었음을 알린다.
  • 또한, setHeader로 헤드를 설정할 수도 있다.
response.setHeader('Content-Type', 'application/json');
response.setHeader('X-Powered-By', 'bacon');
  • 위의 두 코드를 합한 방법으로 더 간단한 writeHead가 있다.
response.writeHead(200, {
  'Content-Type': 'application/json',
  'X-Powered-By': 'bacon'
});
  • 작성한 body의 내용을 response에 담아 보낼 수 있는데, write 나 end를 사용한다.
response.write('Hello' + body);
response.end();

or

response.end("Hello" + body);
  • end를 사용한 이후에는 write를 사용할 수 없다.
if (method === 'POST') {
    let body = [];
    request.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
      body = Buffer.concat(body).toString();
      // body에 문자열로 변환된 request body의 내용이 담겨있다.
      response.end(body.toUpperCase());
      // 대문자로 변환해서 response에 담아 보낸다.
    });
} else {
     response.statusCode = 404;
     response.end("ERROR Method");
}
  • 위와 같이 모든 매소드에 대해서 작동할 수 있도록 코드를 작성해야 한다.

  • 어떤 매소드의 request가 올지 모르기 때문이다.
    (에러를 방지한다.)

profile
🙌🙌🙌🙌

0개의 댓글