response.statusCode 는 상태코드를 지정해서 전달하기가 가능하다. 404 오류 일으킬 수도 있다.

response.setHeader는 header를 설정할 수 있다.

response.writeHead는 위의 두 코드를 간단하게 줄여서 사용이 가능하다.

 

 

 

 

 

상태코드는 200, header의 Content-Type 값이 설정한 대로 되어 있는걸 확인할 수 있다.

 

 

 

 

 

write와 end를 이용해 response body를 만들 수 있다. 다음과 같이 write에 해당 코드 값을 하나하나 넣는 방식도 있고, 

response.end('<html><body><h1>Hello, World!</h1></body></html>');

이 처럼 end에 모든 코드들을 몰아서 집어 넣는 방식도 있다.

 

 

const http = require('http');

http.createServer((request, response) => {
  const { headers, method, url } = request;
  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();

    response.on('error', (err) => {
      console.error(err);
    });

    response.writeHead(200, {'Content-Type': 'application/json'})
    const responseBody = { headers, method, url, body };
    response.end(JSON.stringify(responseBody))
  });
}).listen(8080);

 

 

 

 

 

 

에코서버로 다음과 같이 /echo로 요청하는 post 메소드에 대해서 응답하는 서버를 만들 수 있다.

 

 

 

 

만약 Get 방식으로 서버를 전송했다면 설정한 바와 같이 404 에러가 뜬다.

 

 

 

 

 

POST 방식일 경우 정상적으로 body 값이 응답이 되는걸 확인할 수 있다.

 

 

+ Recent posts