2021년 8월 5일에 작성된 문서 6번 입니다.
node.js의 배운 내용을 정리했습니다.
app.use()
및 app.METHOD()
함수를 이용해 애플리케이션 미들웨어를 앱 인스턴스에 바인드.METHOD
: 소문자로 된 HTTP 메소드// 이 함수는 앱이 요청을 수신할 때마다 실행.
var app = express();
app.use(function (req, res, next) { //마운트 경로가 없다.
console.log('Time:', Date.now());
next();
});
/user/:id
경로에 마운트되는 미들웨어 함수 예시들// `/user/:id` 경로에 대한 모든 유형의 HTTP 요청에 대해 실행
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
-----
// 라우트 및 해당 라우트의 핸들러 함수(미들웨어 시스템)이 표시
// `/user/:id` 경로에 대한 GET 요청을 처리
app.get('/user/:id', function (req, res, next) {
res.send('USER');
});
-----
// 하나의 마운트 경로를 통해 일련의 미들웨어 함수를 하나의 마운트 위치에 로드
// `/user/:id` 경로에 대한
// 모든 유형의 HTTP 요청에 대한 요청 정보를 인쇄하는 미들웨어 하위 스택
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
-----
// 라우트 핸들러를 이용하면 하나의 경로에 대해 여러 라우트를 정의 가능
// `/user/:id` 경로에 대한 GET 요청에 대해 2개의 라우트를 정의
//두 번째 라우트는 어떠한 문제도 발생키지 않지만,
//첫 번째 라우트가 요청-응답 주기를 종료시켜, 두 번째 라우트는 절대로 호출되지 않는다.
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id);
next();
}, function (req, res, next) {
res.send('User Info');
});
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id);
});
-----
// `/user/:id` 경로에 대한 GET 요청을 처리하는 미들웨어 하위 스택이 표시
// 나머지 미들웨어 함수들을 건너뛰려면 `next('route')`를 호출
// 제어를 그 다음 라우트로 전달
//`next('route')`는 `app.METHOD()` 또는 `router.METHOD()`
// 함수를 이용해 로드된 미들웨어 함수에서만 작동
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id);
next();
}, function (req, res, next) {
res.send('User Info');
});
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id);
});
-----
// `/user/:id` 경로에 대한 GET 요청을 처리하는 미들웨어 하위 스택이 표시.
app.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next route
if (req.params.id == 0) next('route');
// otherwise pass the control to the next middleware function in this stack
else next(); //
}, function (req, res, next) {
// render a regular page
res.render('regular');
});
// handler for the /user/:id path, which renders a special page
app.get('/user/:id', function (req, res, next) {
res.render('special');
});
express.Router()
인스턴스에 바인드된다는 점을 제외하고 애플리케이션 레벨 미들웨어와 동일한 방식으로 작동.var router = express.Router();
//`router.use()`,`router.METHOD()` 사용하여 라우터 레벨 미들웨어를 로드
다음 예의 코드는 위에서 애플리케이션 레벨 미들웨어에 대해 표시된 미들웨어 시스템을 라우터 레벨 미들웨어를 사용하여 복제합니다.
var app = express();
var router = express.Router();
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next router
if (req.params.id == 0) next('route');
// otherwise pass control to the next middleware function in this stack
else next(); //
}, function (req, res, next) {
// render a regular page
res.render('regular');
});
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id);
res.render('special');
});
// mount the router on the app
app.use('/', router);
오류 처리 미들웨어에는 항상 4개의 인수가 필요합니다. 어떠한 함수를 오류 처리 미들웨어 함수로 식별하려면 4개의 인수를 제공해야 합니다.
next
오브젝트를 사용할 필요는 없지만, 시그니처를 유지하기 위해 해당 오브젝트를 지정해야 합니다. 그렇지 않으면next
오브젝트는 일반적인 미들웨어로 해석되어 오류 처리에 실패하게 됩니다.
(err, req, res, next)
를 인수로 갖는다app.use(function(err, req, res, next) { //인수 4개는 필수!
console.error(err.stack);
res.status(500).send('Something broke!');
});
express.static
express.static(root, [options])
: Express 애플리케이션의 정적 자산을 제공
root
인수 : 정적 자산의 제공을 시작하는 위치가 되는 루트 디렉토리를 지정options
오브젝트 (선택사항) : 특성 | 설명 | 유형 | 기본값 |
---|---|---|---|
dotfiles | dotfile을 제공하기 위한 옵션입니다. 사용 가능한 값은 “allow”, “deny” 및 “ignore”입니다. | 문자열 | “ignore” |
etag | etag의 생성을 사용 또는 사용 안함으로 설정합니다. | 부울 | true |
extensions | 파일 확장자 폴백을 설정합니다. | 배열 | [] |
index | 디렉토리 인덱스 파일을 전송합니다. 디렉토리 인덱스 작성을 사용하지 않으려면 false 를 설정하십시오. | 혼합 | “index.html” |
lastModified | OS에서 해당 파일이 마지막으로 수정된 날짜를 Last-Modified 헤더에 설정합니다. 사용 가능한 값은 true 또는 false 입니다. | 부울 | true |
maxAge | 밀리초 또는 ms 형식의 문자열로 Cache-Control 헤더의 max-age 특성을 설정합니다. | 숫자 | 0 |
redirect | 경로 이름이 디렉토리인 경우 후미부의 “/”로 경로를 재지정합니다. | 부울 | true |
setHeaders | 파일을 제공하도록 HTTP 헤더를 설정하기 위한 함수입니다. | 함수 |
아래에는 상세한 옵션 오브젝트와 함께
express.static
미들웨어 함수를 사용하는 예가 표시되어 있습니다.
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));
$ npm install cookie-parser
//쿠키 구문 분석 미들웨어 함수인 `cookie-parser`의 설치
//쿠키 구문 분석 미들웨어 함수인 `cookie-parser`의 로드
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// load the cookie-parsing middleware
app.use(cookieParser());
Written with StackEdit.