티스토리 뷰

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마다 설정을 하게 해줘야 할 것이다.

'Web Development > NodeJS' 카테고리의 다른 글

06. express.js Middleware  (0) 2020.03.19
05. express.js  (0) 2020.03.16
03. Hello World in NodeJS  (0) 2020.03.16
02. Node.js 특징  (0) 2020.03.16
01. NodeJS  (0) 2020.03.16
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/05   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함