11강. Express 미들웨어(Middleware)
이번 강의에서는 Express에서 가장 중요한 개념인 미들웨어(Middleware)를 배웁니다.
목표: 요청(Request)과 응답(Response) 사이에서 데이터를 처리하는 미들웨어의 역할을 이해하고 사용할 수 있습니다.
1. 미들웨어란?
미들웨어는 클라이언트의 요청(Request)과 서버의 응답(Response) 사이에서 실행되는 함수입니다.
동작 구조
브라우저
↓
Request
↓
미들웨어
↓
라우터(app.get)
↓
Response
↓
브라우저
2. 미들웨어가 필요한 이유
미들웨어는 다양한 작업을 수행합니다.
로그인 확인
권한 검사
요청 데이터 분석
로그 기록
JSON 변환
파일 업로드
에러 처리
실무에서는 거의 모든 요청이 미들웨어를 거칩니다.
3. app.use()
모든 요청에서 실행되는 미들웨어입니다.
const express = require("express");
const app = express();
app.use((req, res, next) => {
console.log("미들웨어 실행");
next();
});
app.get("/", (req, res) => {
res.send("홈페이지");
});
app.listen(3000);
브라우저 접속
http://localhost:3000
터미널 출력
미들웨어 실행
4. next()
next()는 다음 미들웨어 또는 라우터로 이동시키는 함수입니다.
app.use((req,res,next)=>{
console.log("첫 번째");
next();
});
app.use((req,res,next)=>{
console.log("두 번째");
next();
});
결과
첫 번째
두 번째
5. next()를 호출하지 않으면?
app.use((req,res,next)=>{
console.log("멈춤");
});
브라우저는 계속 로딩 상태가 됩니다.
왜냐하면 다음 작업으로 넘어가지 않기 때문입니다.
6. express.json()
JSON 데이터를 자동으로 객체로 변환합니다.
app.use(express.json());
예시
app.post("/member",(req,res)=>{
console.log(req.body);
res.send("등록");
});
요청
{
"name":"홍길동",
"age":30
}
출력
{
name:"홍길동",
age:30
}
7. express.urlencoded()
HTML Form 데이터를 처리합니다.
app.use(express.urlencoded({
extended:true
}));
예시
<form action="/login" method="POST">
<input name="id">
<input name="password">
<button>로그인</button>
</form>
Node.js
app.post("/login",(req,res)=>{
console.log(req.body);
});
8. req.body
POST 데이터 읽기
app.post("/join",(req,res)=>{
console.log(req.body);
res.send("가입완료");
});
입력
id=admin
password=1234
출력
{
id:'admin',
password:'1234'
}
9. 특정 주소만 실행
app.use("/admin",(req,res,next)=>{
console.log("관리자 접근");
next();
});
다음 주소에서만 실행됩니다.
/admin
/admin/list
/admin/write
10. 로그인 검사
function loginCheck(req,res,next){
console.log("로그인 확인");
next();
}
app.get("/mypage",loginCheck,(req,res)=>{
res.send("마이페이지");
});
실행 순서
브라우저
↓
로그인 검사
↓
마이페이지
11. 여러 미들웨어
function one(req,res,next){
console.log("1");
next();
}
function two(req,res,next){
console.log("2");
next();
}
app.get("/",one,two,(req,res)=>{
res.send("OK");
});
결과
1
2
OK
12. 로그 기록
app.use((req,res,next)=>{
console.log(req.method);
console.log(req.url);
next();
});
출력
GET
/about
13. 현재 시간 출력
app.use((req,res,next)=>{
console.log(new Date());
next();
});
모든 요청 시간을 기록할 수 있습니다.
14. 실무에서 많이 사용하는 미들웨어
미들웨어 기능
express.json() JSON 처리
express.urlencoded() Form 처리
Logger 로그 저장
Session 로그인 유지
JWT 인증
Multer 파일 업로드
CORS 다른 서버 접근 허용
15. 실습 1
모든 요청 기록
app.use((req,res,next)=>{
console.log("접속");
next();
});
16. 실습 2
주소 출력
app.use((req,res,next)=>{
console.log(req.url);
next();
});
17. 실습 3
메소드 출력
app.use((req,res,next)=>{
console.log(req.method);
next();
});
18. 실습 4
로그인 검사
function auth(req,res,next){
console.log("인증");
next();
}
app.get("/admin",auth,(req,res)=>{
res.send("관리자");
});
19. Express 실행 순서
브라우저
↓
app.use()
↓
app.use()
↓
app.get()
↓
응답
↓
브라우저
20. 이번 강의 핵심 정리
문법 설명
app.use() 미들웨어 등록
next() 다음 작업으로 이동
express.json() JSON 데이터 처리
express.urlencoded() Form 데이터 처리
req.body POST 데이터
req.method 요청 방식
req.url 요청 주소
실무 팁
실제 프로젝트에서는 다음과 같이 미들웨어를 가장 먼저 등록하는 경우가 많습니다.
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// 이후 라우터 등록
app.get("/", (req, res) => {
res.send("Hello Express");
});
이렇게 하면 모든 요청에 대해 JSON 처리, 폼 데이터 처리, 요청 로그 기록이 자동으로 적용됩니다.
실습 미션
간단한 회원가입 API를 만들어 보세요.
express.json() 등록
POST /join 생성
req.body로 이름과 나이 받기
받은 데이터를 콘솔에 출력
"회원가입 완료" 응답 보내기
예시 요청(JSON)
{
"name": "커사맨",
"age": 50
}
이번 강의에서는 Express에서 가장 중요한 개념인 미들웨어(Middleware)를 배웁니다.
목표: 요청(Request)과 응답(Response) 사이에서 데이터를 처리하는 미들웨어의 역할을 이해하고 사용할 수 있습니다.
1. 미들웨어란?
미들웨어는 클라이언트의 요청(Request)과 서버의 응답(Response) 사이에서 실행되는 함수입니다.
동작 구조
브라우저
↓
Request
↓
미들웨어
↓
라우터(app.get)
↓
Response
↓
브라우저
2. 미들웨어가 필요한 이유
미들웨어는 다양한 작업을 수행합니다.
로그인 확인
권한 검사
요청 데이터 분석
로그 기록
JSON 변환
파일 업로드
에러 처리
실무에서는 거의 모든 요청이 미들웨어를 거칩니다.
3. app.use()
모든 요청에서 실행되는 미들웨어입니다.
const express = require("express");
const app = express();
app.use((req, res, next) => {
console.log("미들웨어 실행");
next();
});
app.get("/", (req, res) => {
res.send("홈페이지");
});
app.listen(3000);
브라우저 접속
http://localhost:3000
터미널 출력
미들웨어 실행
4. next()
next()는 다음 미들웨어 또는 라우터로 이동시키는 함수입니다.
app.use((req,res,next)=>{
console.log("첫 번째");
next();
});
app.use((req,res,next)=>{
console.log("두 번째");
next();
});
결과
첫 번째
두 번째
5. next()를 호출하지 않으면?
app.use((req,res,next)=>{
console.log("멈춤");
});
브라우저는 계속 로딩 상태가 됩니다.
왜냐하면 다음 작업으로 넘어가지 않기 때문입니다.
6. express.json()
JSON 데이터를 자동으로 객체로 변환합니다.
app.use(express.json());
예시
app.post("/member",(req,res)=>{
console.log(req.body);
res.send("등록");
});
요청
{
"name":"홍길동",
"age":30
}
출력
{
name:"홍길동",
age:30
}
7. express.urlencoded()
HTML Form 데이터를 처리합니다.
app.use(express.urlencoded({
extended:true
}));
예시
<form action="/login" method="POST">
<input name="id">
<input name="password">
<button>로그인</button>
</form>
Node.js
app.post("/login",(req,res)=>{
console.log(req.body);
});
8. req.body
POST 데이터 읽기
app.post("/join",(req,res)=>{
console.log(req.body);
res.send("가입완료");
});
입력
id=admin
password=1234
출력
{
id:'admin',
password:'1234'
}
9. 특정 주소만 실행
app.use("/admin",(req,res,next)=>{
console.log("관리자 접근");
next();
});
다음 주소에서만 실행됩니다.
/admin
/admin/list
/admin/write
10. 로그인 검사
function loginCheck(req,res,next){
console.log("로그인 확인");
next();
}
app.get("/mypage",loginCheck,(req,res)=>{
res.send("마이페이지");
});
실행 순서
브라우저
↓
로그인 검사
↓
마이페이지
11. 여러 미들웨어
function one(req,res,next){
console.log("1");
next();
}
function two(req,res,next){
console.log("2");
next();
}
app.get("/",one,two,(req,res)=>{
res.send("OK");
});
결과
1
2
OK
12. 로그 기록
app.use((req,res,next)=>{
console.log(req.method);
console.log(req.url);
next();
});
출력
GET
/about
13. 현재 시간 출력
app.use((req,res,next)=>{
console.log(new Date());
next();
});
모든 요청 시간을 기록할 수 있습니다.
14. 실무에서 많이 사용하는 미들웨어
미들웨어 기능
express.json() JSON 처리
express.urlencoded() Form 처리
Logger 로그 저장
Session 로그인 유지
JWT 인증
Multer 파일 업로드
CORS 다른 서버 접근 허용
15. 실습 1
모든 요청 기록
app.use((req,res,next)=>{
console.log("접속");
next();
});
16. 실습 2
주소 출력
app.use((req,res,next)=>{
console.log(req.url);
next();
});
17. 실습 3
메소드 출력
app.use((req,res,next)=>{
console.log(req.method);
next();
});
18. 실습 4
로그인 검사
function auth(req,res,next){
console.log("인증");
next();
}
app.get("/admin",auth,(req,res)=>{
res.send("관리자");
});
19. Express 실행 순서
브라우저
↓
app.use()
↓
app.use()
↓
app.get()
↓
응답
↓
브라우저
20. 이번 강의 핵심 정리
문법 설명
app.use() 미들웨어 등록
next() 다음 작업으로 이동
express.json() JSON 데이터 처리
express.urlencoded() Form 데이터 처리
req.body POST 데이터
req.method 요청 방식
req.url 요청 주소
실무 팁
실제 프로젝트에서는 다음과 같이 미들웨어를 가장 먼저 등록하는 경우가 많습니다.
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// 이후 라우터 등록
app.get("/", (req, res) => {
res.send("Hello Express");
});
이렇게 하면 모든 요청에 대해 JSON 처리, 폼 데이터 처리, 요청 로그 기록이 자동으로 적용됩니다.
실습 미션
간단한 회원가입 API를 만들어 보세요.
express.json() 등록
POST /join 생성
req.body로 이름과 나이 받기
받은 데이터를 콘솔에 출력
"회원가입 완료" 응답 보내기
예시 요청(JSON)
{
"name": "커사맨",
"age": 50
}
#11강. Express 미들웨어(Middleware)