URL에 따른 백엔드

데브코스

목록 보기
9/131

URL : Uniform Resource Locator
= 인터넷 상에서 웹 페이지가 어디있는지 "위치"를 알려주는 주소 입니다.
쉽게 말해서, 웹 페이지 주소라고 할 수 있다.

그래서 localhost 라는 것이 내 컴퓨터 주소를 나타낸다.


pathname : http://localhost:8888 이 뒤에 오는 경로가 pathname이라고 해. http://localhost:8888/hello 같은 걸 말하지.

Router : 경로를 정해주는 친구.

서버에서 루트를 사용할 수 있도록
route(pathname)

루트를 밖에서 받는거야.
function start(route)

그럼 저 startdml route를 전달해주는 친구가 누구인가요?

일단 라우터 모듈꺼겠죠? 그래서 라우터 모듈을 소환해요.

let router = require('./router');

index.js에 있는 server.start(router.route)에서 루트를 전달해줄거야.



index.js에서 server.js를 구동시키고 server.js는 router.js 에서 어디로 갈지 길만 정해주는 얘야.
그 길을 route라고 하는데, 아직 거기까진 안정해준거야. 저 그림상으론 ㅇㅋ?

server.js

let http = require("http");
let url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    let pathname = url.parse(request.url).pathname;

    route(pathname, handle, response); // 서버가 루트에게 pathname을 넘겨줌.

  }

  http.createServer(onRequest).listen(8888);
  // localhost:8888
}

exports.start = start;

router.js

function route(pathname, handle, response) {
  console.log("pathname : " + pathname);

  if (typeof handle[pathname] == "function") {
    handle[pathname](response); //핸들러 객체에서 pathname에 해당하는 함수를 호출
  } else {
    response.writeHead(404, { "Content-Type": "text/html" });
    response.write("Not found");
    response.end();
  }
}
exports.route = route;


index.js

let server = require("./server");

let router = require("./router");
let requestHandler = require("./requestHandler");

server.start(router.route, requestHandler.handle);

requestHandler.js

//각 루트별 요청을 진행하는 핸들러

function main(response) {
  console.log("main");

  response.writeHead(200, { "Content-Type": "text/html" });
  response.write("Main page");
  response.end();
}

function login(response) {
  console.log("login");

  response.writeHead(200, { "Content-Type": "text/html" });
  response.write("login page");
  response.end();
}

function favicon() {
  console.log("favicon");
}

let handle = {}; //key:value 쌍으로 저장

handle["/"] = main;
handle["/login"] = login;
handle["/favicon.ico"] = favicon;

exports.handle = handle;
profile
Dive Head First | Work Super Hard | Attract Great People

0개의 댓글