카테고리 없음

Nodejs controller 분리(1-5)

Canyi 2022. 10. 2. 20:50

현재 이 진한 색상 부분이  컨트롤러

여기서 router는 단순히 "/login" 이라는 도메인에 들어왔을때 클라인터트에 요청을 연결해주는 역할은 한다. 실제로

router.get("/login" 의 기능을 수행하는 부분은
 
(request, response)=>{
response.render("home/login")
}

 이 부분이다. 즉 이부분이 컨트롤러 이다. 바로 이런 부분들을 따로 분리를 할것이다.

routes/home > home/ctrl.js라는 파일을 만들고 home이라는 함수를 만들고 controller부분을  넣는다.

 

router.get("/",home);

app.js에서는 같은 경로에 있는 home함수를 불러온다. 똑같이 로그인 부분 컨트롤러도 분리를 해준다.

 

그리고 라우팅 분리를 할 때 처럼

module.exports 기능을 사용해  home, login 기능을 다른 파일에 사용할수 있도록 선언한다.

Object의 key와 value처럼 여기서 {home, login,}; 은  {home: home, login:login}; 과 같다. 

 

갹체를 home.ctrl.js에서 넘겨줬으면 index.js에서 받아와야 한다.

그러면 

const ctrl = require("./home.ctrl"); 를 불러온다.

index.js에 ctrl이라는 함수를 선언했기에  router,get에서 ctrl.home 과 ctrl.login을 불러온다.

node app.js를 사용해서 서버를 가동하고 http://localhost:3000/  과  http://localhost:3000/login 을 확인해본다.

각각 실행이 잘 된다!! 

 

home.ctrl.js 전체코드

"use strict";    //이크마 스크립트

const home =
    (request, response) => {
        response.render("home/index")
    };

const login =
    (request, response) => {
        response.render("home/login")
    };

module.exports = {
    
    home,
    login,

    /*
        위코드와 같다. object 의 key 와 value
        {
            key: valyue,
            home: home,
            login:login,
        }
    */
};

index.js 전체 코드

"use strict";  //이크마 스크립트 표준 준수

const express  = require("express");  
const router  = express.Router();

const ctrl = require("./home.ctrl");

router.get("/",ctrl.home);        
router.get("/login", ctrl.login);

module.exports = router;

 

Nodejs app.listen() 모듈화(1-6)

https://piaocanyi.tistory.com/188