Web Development/NodeJS

04. NodeJs URL처리

tongnamuu 2020. 3. 16. 02:38

우선은 terminal을 하나 더 열고

curl -X GET "localhost:3000"

를 실행해보면 Hello World가 찍힐 것이다.

서버가 listen의 대기상태이고 요청이 들어올 때 마다 해당 서버 코드의 콜백함수가 동작하는 것이다.

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World");
});

이때 아래를 실행해도 Hello World가 찍힐 것이다. 그렇다면 /intro는 어디에 있는 것일까?

curl -X GET "localhost:3000/intro"

정답은 저 곳의 req에 있다.

req.url을 console.log 해보자.

const server = http.createServer((req, res) => {
  console.log(req.url);
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World");
});

이후 다시

curl -X GET "localhost:3000/intro"

실행해보자

즉 request에 url정보가 들어가는 것이다. 이 때 만약에 다른 url로 들어오는 경우 다른 응답을 하거나 혹은 404 Not Found를 돌려주고 싶을 수도 있을 것이다. 이렇게 하게 되면 각각의 url마다 설정을 하게 해줘야 할 것이다.