<-->
본문 바로가기

프로그래밍/nodeJS

HTTP 모듈로 '간단한' 웹서버 구축하기

반응형

웹서버 : 클라이언트가 요청한 정보를 서버의 로직으로 처리하여 여러가지 형태로 응답해주는 도구

 

 

const http = require("http"),
httpStatus = require("http-status-codes"),
port =3000;

const app =http.createServer((req,res)=> { //서버 인스턴스 생성(HTTP통신을 위한 도구)
  res.writeHead(httpStatus.OK, { //응답 컨텐츠의 기본 속성 설정
    "Content-Type":"text/html"
  });
  console.log(`method: ${req.method}`);
  console.log(`url: ${req.url}`);

  res.write('<h1> write response! </h1>'); //응답중
  res.end(`<h1>end response! </h1> `); //응답끝
});

app.listen(port);

http.createServer((req,res)=> {}

요청이벤트가 들어올때마다 매개변수가 req(요청 정보 담긴 객체)와 res(응답 내용 담을 객체)인 콜백함수를 실행시킨다.

*파란색 부분이 콜백함수

 

req 객체

클라이언트가 요청한 정보인 method(POST,GET 등등), url(라우트), 헤더 등등 이 담겨있다. 

 

req객체의 method, url 속성

res 객체

클라이언트에 응답할 내용을 담을 수 있다. 

위의 코드에서는 res.write(), res.end() 메소드에 담아서 응답했다

 

결과