Express 사용기[3] - Advanced 라우팅

김진성·2021년 10월 16일
1

Node.js

목록 보기
3/5
post-thumbnail

라우팅 Advanced 버전

app.all()

app.all() 이라는 특수한 라우팅 메소드가 존재하는데 이는 HTTP 메소드로부터 파생된 것이 아니다. 이 메소드는 모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는데 사용된다.

app.all('/secret', function (req, res, next) { 
	console.log('Accessing the secret section ...');
    next(); //next 핸들러로 사용권을 넘기는 느낌
});

라우트 경로

라우트 경로는 URL 엔드포인트를 의미한다. velog.io 사이트 뒤에 / or /guri, /coding이 붙으면 이러한 경로를 라우트 경로라 한다. 이러한 라우트 경로는 문자열, 문자열 패턴 또는 정규식으로 구성되어 있다. 기본 라우트 경로 같은 경우 앞에서 봤기 때문에 문자열 패턴 기반 라우트 예시를 설명하도록 하겠다.

1. acd == abcd 인 경우

b가 있어도 되고 없어도 되는 경우
app.get('/ab?cd', function(req, res) {
	res.send('ab?cd');
})

2. abcd == abbcd == abbbcd 인 경우

b가 한 개 이상일 경우
app.get('/ab+cd', function(req, res) {
	res.send('ab+cd');
})

3. abcd == abxcd == abRABDOMcd == ab123cd 인 경우

문자열이나 숫자가 들어와도 상관이 없는 경우 양끝만 일치하면 된다.
app.get('/ab*cd', function(req, res) {
	res.send('ab*cd');
})

4. abe == abcde 인 경우

1번 경우와 비슷하게 cd가 동시에 있어도 되고 없어도 되는 경우
app.get('/ab(cd)?e', function(req, res) {
	res.send('ab(cd)?e');
})

5. a가 포함된 경우 모든 항목과 일치

app.get('/a/', function(req, res) {
	res.send('/a/');
})

6. 앞에 문자열이 붙어도 되지만 뒤에는 붙이면 안되는 경우

app.get('/.*fly$/', function(req, res) {
	res.send('/.*fly$/');
})

라우트 핸들러

미들웨어와 비슷하게 작동되는 여러 콜백 함수를 제공하여 요청을 처리할 수 있다. 예를 들면, req, res를 서버로 받아서 응답을 해주는 함수를 제공해준다는 의미이다. 미들웨어와 유일한 차이점은 next('route')를 호출하여 나머지 라우트 콜백을 우회할 수 있다. 그래서 라우트가 사전 조건에 따라서 제어를 후속 라우트에 전달할 수 있다는 점이다.

1. 콜백 함수가 한 개인 경우

//한 개인 경우
app.get('/example/a', function (req, res) {
	res.send('Hello from A!);
})

2. 콜백 함수가 두 개 이상인 경우

//2개 이상의 콜백 함수가 있을 경우
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!');
});

3. 많은 콜백 함수를 배열로 표현할 경우

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

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

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

app.get('/example/c', [cb0, cb1, cb2]);

4. 배열과 독립적인 콜백 함수로 동시에 처리할 경우

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

var 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!');
});

응답 메소드

콜백 함수의 파라미터인 res에서 사용가능한 메소드에 대해서 정리하자면 아래와 같다.

res.download() : 파일이 다운로드되도록 프롬프트를 진행
res.end() : 응답 프로세스를 종료
res.json() : JSON 응답을 전송
res.jsonp() : JSONP 지원을 통해 JSON 응답을 전송
res.redirect() : 요청의 경로를 재지정
res.render() : View 템플릿을 렌더링함
res.send() : 다양한 유형의 응답을 전송
res.sendFile() : 파일을 옥텟 스트림의 형태로 전송
res.sendStatus() : 응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 응답 본문으로서 전송

app.route()

app.route() 를 사용하면 라우트 경로에 대하여 각 HTTP 메소드 별로 응답을 대응할 수 있다. 아래의 예시는 /book으로 들어온 요청에 대하여 GET, POST, PUT 별로 각각 응답을 보낼 수 있는 것을 보여준다.

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 클래스를 사용할 경우 라우터를 모듈러로 작성하고 라우터 모듈에서 미들웨어 함수를 로드하는 등 하나의 앱에 다양한 기능을 가진 모듈을 만들 수 있다.

var express = require('express');
var router = express.Router();

router.use(function timeLog(req, res, next) {
	console.log('Time: ', Date.now());
    next();
});

router.get('/', function(req, res) {
	res.send('Birds home page');
});

router.get('/about', function(req, res) {
	res.send('About birds');
});

module.exports = router;

만약 위 라우터를 작성한 파일 이름이 birds.js 라면 모듈을 받아올 때는 birds라는 이름으로 가져올 수 있다.

var birds = require('./birds');
...
app.use('/birds', birds);
profile
https://medium.com/@jinsung1048 미디엄으로 이전하였습니다.

0개의 댓글