개인공부/TIL(Today I Learned)

TIL 64일차_Express.js : 라우팅

soon327 2021. 3. 23. 01:59

Express.js는 Node.js를 위한 웹 프레임워크 중 하나이다.
express가 기존 http 모듈로 작성하는 서버와 갖는 큰 차이점은 다음과 같다.

  1. 미들웨어를 붙이기 쉽다.
  2. 자체 라우터를 제공한다.

express 설치하기

Express.js는 npm으로 설치한다.
npm init npm install express --save 순서로 쉽게 설치할 수 있다.

express : Hello world

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello world!');
});

app.listen(port, () => {
    //node app.js 실행시 터미널에 출력됨
  console.log(`Example app listening at http://localhost:${port}`); 
});

앱은 서버를 시작하며 3000번 포트에서 연결을 listen한다.
앱은 루트 URL(/) 또는 라우트에 대한 요청에 “Hello World!”로 응답하며,
다른 모든 경로에 대해서는 404 Not Found로 응답한다.

req(요청) 및 res(응답)는 Node가 제공하는 동일한 오브젝트이며,
따라서 req.pipe(), req.on('data', callback),
그리고 Express의 관여가 필요 없는 다른 모든 항목을 호출할 수 있다.

express : 라우팅(routing)

라우팅은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)
특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것을 말한다.

express 라우팅 기본 구조

app.METHOD(PATH, HANDLER)

app.get('/', function (req, res) {
    res.send('Hello World!');
  });

라우트 핸들러

하나의 라우트를 처리할 때, 2개이상의 콜백함수로 처리할 수도 있다.
즉, 위의 라우팅 기본구조에서 HANDLER로 들어가는 콜백함수가 여러개일 수 있다는 것이다.
이때는 next 오브젝트를 반드시 지정해야한다.

(예시)

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});

라우트 핸들러는 함수나 함수배열, 또는 둘을 조합한 형태일 수 있다.

const cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

const cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

const cb2 = function (req, res) {
  res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);
const cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

const cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});

response 메소드

라우트핸들러로부터 다음 표에 표시된 response메소드 중 어느 하나도 호출되지 않는 경우,
클라이언트 요청은 정지된 채로 방치된다.

app.route()

app.route()를 사용하면, 하나의 라우트경로에서 체이닝을 통해
체인 라우트 핸들러를 작성할 수 있다.

app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });

express.Router

express.Router 클래스를 사용하면 모듈식 마운팅 가능한 핸들러를 작성할 수 있다.
Router 인스턴스는 완전한 미들웨어이자 라우팅 시스템이며,
따라서 “미니 앱(mini-app)”이라고 불리는 경우가 많습니다.

// birds.js라는 이름으로 저장
const express = require('express');
const router = express.Router();

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

이후, 앱 내에서 다음과 같이 라우트모듈을 로드하면,

const birds = require('./birds');
...
app.use('/birds', birds);

/birds 및 '/birds/about'에 대한 요청을 처리할 수 있게 되며,
해당 라우트에 대한 특정한 미들웨어 함수인 timeLog를 호출하게 된다.

출처: Express.js 공식문서

'개인공부 > TIL(Today I Learned)' 카테고리의 다른 글

TIL 66일차_React : JSX  (0) 2021.03.25
TIL 65일차_npm vs npx  (0) 2021.03.24
TIL 63일차_git: local - remote 연결  (0) 2021.03.22
TIL 62일차_Git: .gitignore  (0) 2021.03.21
TIL 61일차_ChatterBox  (0) 2021.03.20