728x90
https://opentutorials.org/course/3370
생활코딩님의 Express.js강의를 참고하였습니다.
1.미들웨어
요청(Request)과 응답(Response) 사이에서 특정 작업을 수행하는 함수
요청이 처리되는 과정에서 여러 단계를 거쳐 특정 작업을 실행하고, 다음 단계로 요청을 넘기거나 응답을 보냅니다.
app.use로 미들웨어를 등록합니다.
- 클라이언트가 서버에 요청을 보냅니다.
- 요청이 처음 등록된 미들웨어부터 처리됩니다.
- 각 미들웨어는 next()를 호출해 다음 미들웨어로 요청을 넘기거나, 요청에 대한 응답을 처리할 수 있습니다.
- 응답을 처리할 수 있는 미들웨어에 도달하면 클라이언트로 응답이 전송됩니다.
2.미들웨어 구조
req: 요청 객체 (request)
res: 응답 객체 (response)
next: 다음 미들웨어를 호출하는 함수
//기본적인 구조
function middleware(req, res, next) {
// 미들웨어 로직
// 다음 미들웨어를 호출
next();
}
//예시
// 모든 요청에 대해 실행되는 미들웨어
app.use((req, res, next) => {
console.log('Request URL:', req.url);
next(); // 다음 미들웨어로 넘김
});
3.미들웨어 종류
3-1.애플리케이션 수준 미들웨어
애플리케이션 전체에 적용되는 미들웨어
const express = require('express');
const app = express();
// 모든 요청에 대해 실행되는 미들웨어
app.use((req, res, next) => {
console.log('Request URL:', req.url);
next(); // 다음 미들웨어로 넘김
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000);
3-2.라우터 수준 미들웨어
특정 라우터에만 적용되는 미들웨어
const express = require('express');
const app = express();
const router = express.Router();
// 특정 라우트에 적용되는 미들웨어
router.use((req, res, next) => {
console.log('Router-specific middleware');
next();
});
router.get('/user/:id', (req, res) => {
res.send('User Info');
});
app.use('/users', router); // '/users' 경로에 대해 라우터 미들웨어 적용
3-3.내장 미들웨어
Express는 몇 가지 내장 미들웨어를 제공합니다.
app.use(express.json()); // JSON 형식의 요청을 파싱하는 미들웨어
app.use(express.static('public')); // 정적 파일을 제공하는 미들웨어
3-4.서드파티 미들웨어
morgan, body-parser와 같은 외부 라이브러리에서 제공하는 미들웨어
const morgan = require('morgan');
app.use(morgan('dev')); // 로그를 출력하는 미들웨어
728x90
'BackEnd > Express.js' 카테고리의 다른 글
[Express.js] body-parser (0) | 2024.09.09 |
---|---|
[Express.js] 삭제 기능 (0) | 2024.09.09 |
[Express.js] 수정기능 (0) | 2024.09.09 |