2021년 8월 5일에 작성된 문서 3번 입니다.
node.js의 배운 내용을 정리했습니다.
var express = require('express');
var app = express();
//홈페이지에 get요청이 도착을 하면,
app.get('/', function(req, res) {
res.send('hello world');
// "hello world"라고 답을 줌.
}); //라우팅 기본 방식
express
클래스의 인스턴스에 연결var app = express();
: express 클래스 인스턴스는 app이니까 여기에 연결.// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});
// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
app.all()
app.all('/secret', function (req, res, next) {
// GET, POST, PUT 또는 DELETE 메소드를 사용하는 경우
// 또는 http 모듈에서 지원되는 기타 모든 HTTP 요청 메소드를 사용하는 경우
// secret에 대한 요청을 위하여 핸들러가 실행
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
app.get('/', function (req, res) {
//라우트 경로는 요청을 루트 라우트 `/`에 일치
res.send('root');
});
app.get('/about', function (req, res) {
//라우트 경로는 요청을 `/about`에 일치
res.send('about');
});
미들웨어와 비슷하게 작동하는 여러 콜백 함수를 제공하여 요청을 처리할 수 있다.
이 콜백은next('route')
를 호출하여 나머지 라우트 콜백을 우회할 수도 있다.
이러한 메커니즘을 이용하면 라우트에 대한 사전 조건을 지정한 후, 현재의 라우트를 계속할 이유가 없는 경우에는 제어를 후속 라우트에 전달할 수 있다.
//라우트 핸들러는 함수나 함수 배열의 형태 또는 둘을 조합한 형태
//하나의 콜백 함수는 하나의 라우트를 처리할 수 있다.
app.get('/example/a', function (req, res) {
//여기가 콜백 함수 부분 => 요청 처리
res.send('Hello from A!');
});
//2개 이상의 콜백 함수는 하나의 라우트를 처리
//이 때는 반드시 next 오브젝트를 지정해야 한다.
app.get('/example/b', function (req, res, next) { //콜백 1번
console.log('the response will be sent by the next function ...');
next(); //next 오브젝트를 지정
}, function (req, res) { //콜백 2번
res.send('Hello from B!');
});
//하나의 콜백 함수 배열은 하나의 라우트를 처리할 수 있다.
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]);
//독립적인 함수와 함수 배열의 조합은 하나의 라우트를 처리할 수 있다.
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.download(경로,[파일명],[옵션들],[fn]) | 파일이 다운로드되도록 프롬프트 |
res.end() | res.end([data],[인코딩 형식]) | 응답 프로세스를 종료 |
res.json() | res.json([바디]) | JSON 응답을 전송 |
res.jsonp() | res.jsonp([바디]) | JSONP 지원을 통해 JSON 응답을 전송 |
res.redirect() | res.redirect([상태], 경로) | 요청의 경로를 재지정 |
res.render() | res.render(보기 템플릿,[locals],[콜백]) | 보기 템플리트를 렌더링 |
res.send() | res.send([바디]) | 다양한 유형의 응답을 전송 |
res.sendFile() | res.sendFile(경로,[옵션들],[fn]) | 파일을 옥텟 스트림의 형태로 전송 |
res.sendStatus() | res.sendStatus(상태 코드) | 응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 내용을 응답 본문으로서 전송 |
//체인 라우트 핸들러의 예시 (체인 형식)
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');
});
Router
인스턴스는 완전한 미들웨어이자 라우팅 시스템//라우터를 모듈로서 작성하고,
//라우터 모듈에서 미들웨어 함수를 로드하고,
//몇몇 라우트를 정의하고, 기본 앱의 한 경로에 라우터 모듈을 마운트
var express = require('express');
var 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;
Written with StackEdit.