goal
- 라우터에 대해서 알아보자
라우팅은 URI (or path) 및 특정 http 요청메소드인 특정 endpoint에 대한 클라이언트 요청에, 애플리케이션이 응답하는 방법을 결정하는 것을 뜻한다.
하나 이상의 핸들러 함수를 가질 수 있으며, 이러한 함수는 라우트가 일치할 때만 실행된다.
app.METHOD ( PATH, HANDLER ) |
---|
METHOD : http 요청 메서드 |
PATH : 서버 경로 |
HANDLER : 라우트가 일치할 때 실행되는 함수 |
예
// 홈페이지에서 Hollw World!로 응답
app.get('/', function (req, res) {
res.send('Hello World!');
});
// 루트라우트(/)에서 post 요청에 응답
app.post('/', function (req, res) {
res.send('Got a POST request');
});
// user라우트(/user)에서 post 요청에 응답
app.post('/user', function (req, res) {
res.send('Got a POST request');
});
app['m-search']('/', function ...
app.all()
은 어떠한 HTTP 메소드로부터도 파생되지 않는다. 이 메소드는 "모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는 데 사용"된다.app.get('/example/a', function (req, res) {
res.send('Hello from A!');
});
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!');
});
method | description |
---|---|
res.download() | 파일이 다운로드되도록 프롬프트 |
res.end() | 응답 프로세스를 종료 |
res.json() | json응답을 전송 |
res.jsonp() | jsonp지원을 통해 json응답을 전송 |
res.redirect() | 요청의 경로를 재지정 |
res.render() | view 템플릿을 렌더링 |
res.send() | 다양한 유형의 응답을 전송 |
res.sendFile | 파일을 octet stream 형태로 전송 |
res.sendStatus() | 응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 내용을 응답 본문으로서 전송 |
// 1
var express = require('express');
var router = express.Router();
// 2
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// 3
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// 4
module.exports = router;