Express에서 라우팅은 HTTP 메서드와 경로를 함수에 연결하는 일이고, 미들웨어는 그 함수에 닿기 전후로 요청이 거쳐 가는 함수입니다. REST API 하나는 express.json(), 라우터 모듈, 검증 미들웨어, 404 처리, 에러 처리 미들웨어를 등록 순서에 맞게 쌓으면 완성됩니다. 이 글에서는 메모리에 저장하는 할 일 목록 API를 만들고, 요청마다 curl -i로 실제 응답을 확인합니다.
준비물
| 항목 | 내용 |
|---|---|
| Node.js | v24.15.0 |
| npm | 11.12.1 |
| Express | 4.21.2 |
| 확인 도구 | curl (Windows 10 이상에 기본 포함) |
| 셸 | Git Bash (작은따옴표로 JSON을 감싸는 명령을 그대로 쓰기 위해) |
서버는 127.0.0.1에만 엽니다. 다른 PC에서는 접속할 수 없습니다.
1. 프로젝트와 Express 설치
빈 폴더에서 프로젝트를 만들고 Express를 설치합니다.
npm init -y
npm install express@4.21.2
npm ls
added 69 packages, and audited 70 packages in 2s
4 vulnerabilities (1 moderate, 3 high)
`-- express@4.21.2
출력에서 funding 안내와 폴더 경로 줄은 뺐습니다. 설치 직후 경고 4건이 나옵니다. Express가 함께 가져오는 body-parser, path-to-regexp, qs에 보고된 서비스 거부 취약점이고, npm audit은 npm audit fix로 고칠 수 있다고 알려 줍니다. 이 글에서는 4.21.2를 그대로 씁니다. 경고를 읽고 고치는 순서는 npm audit 점검 글에 있습니다.
파일은 세 개로 나눕니다.
app.js 앱 조립: 미들웨어 등록 순서가 여기서 정해진다
middleware/logger.js 로깅 미들웨어
routes/todos.js /todos 라우터 모듈
2. 로깅 미들웨어
미들웨어는 (req, res, next)를 받는 함수입니다. 제 일을 마치고 next()를 부르면 다음 미들웨어로 넘어갑니다. 부르지 않으면 요청이 거기서 멈추고 응답이 끝나지 않습니다.
// middleware/logger.js
function logger(req, res, next) {
const started = Date.now();
res.on("finish", () => {
const ms = Date.now() - started;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
});
next();
}
module.exports = logger;
상태 코드는 응답이 끝나야 알 수 있으므로 finish 이벤트에서 기록합니다.
3. 라우터 모듈
express.Router()는 라우트를 묶어 파일 하나로 떼어 내는 작은 앱입니다. 이 파일 안의 경로는 /로 시작하고, 앞에 붙는 /todos는 app.js에서 정합니다.
// routes/todos.js
const express = require("express");
const router = express.Router();
let nextId = 3;
const todos = [
{ id: 1, title: "install express", done: true },
{ id: 2, title: "split router", done: false },
];
// :id가 들어온 모든 라우트보다 먼저 실행된다
router.param("id", (req, res, next, value) => {
if (!/^[1-9][0-9]*$/.test(value)) {
return res.status(400).json({ error: "id must be a positive integer" });
}
const todo = todos.find((t) => t.id === Number(value));
if (!todo) {
return res.status(404).json({ error: "todo not found" });
}
req.todo = todo;
next();
});
function validateBody(req, res, next) {
const { title, done } = req.body || {};
if (typeof title !== "string" || title.trim() === "") {
return res.status(400).json({ error: "title must be a non-empty string" });
}
if (title.length > 100) {
return res.status(400).json({ error: "title must be 100 characters or fewer" });
}
if (done !== undefined && typeof done !== "boolean") {
return res.status(400).json({ error: "done must be a boolean" });
}
next();
}
router.get("/", (req, res) => {
res.json(todos);
});
router.get("/boom", (req, res) => {
throw new Error("demo failure");
});
router.get("/:id", (req, res) => {
res.json(req.todo);
});
router.post("/", validateBody, (req, res) => {
const todo = { id: nextId++, title: req.body.title.trim(), done: req.body.done === true };
todos.push(todo);
res.status(201).location(`/todos/${todo.id}`).json(todo);
});
router.put("/:id", validateBody, (req, res) => {
req.todo.title = req.body.title.trim();
req.todo.done = req.body.done === true;
res.json(req.todo);
});
router.delete("/:id", (req, res) => {
todos.splice(todos.indexOf(req.todo), 1);
res.status(204).end();
});
module.exports = router;
코드에서 볼 곳은 세 군데입니다.
- 라우트 단위 미들웨어:
router.post("/", validateBody, handler)처럼 경로 뒤에 함수를 여러 개 넣으면 왼쪽부터 실행됩니다.validateBody가 400으로 응답하고next()를 부르지 않으면 handler는 실행되지 않습니다. router.param: 경로의:id를 한 곳에서 검사합니다. GET, PUT, DELETE가 같은 검사를 반복하지 않아도 됩니다.- 라우트 순서:
/boom은/:id보다 위에 있습니다. 순서를 바꿔 아래에 두고 요청해 보니boom이:id값으로 잡혀 400이 나왔습니다./boom은 6번 절에서 에러 처리를 확인하려고 넣은 라우트입니다.
4. 앱 조립과 등록 순서
// app.js
const express = require("express");
const logger = require("./middleware/logger");
const todosRouter = require("./routes/todos");
const port = Number(process.argv[2] || 4201);
const app = express();
app.use(logger);
app.use(express.json());
app.use("/todos", todosRouter);
// 어느 라우트에도 걸리지 않은 요청
app.use((req, res) => {
res.status(404).json({ error: "not found", path: req.originalUrl });
});
// 인자가 4개면 Express가 에러 처리 미들웨어로 취급한다
app.use((err, req, res, next) => {
if (err.type === "entity.parse.failed") {
return res.status(400).json({ error: "invalid JSON body" });
}
console.error("unhandled:", err.message);
res.status(500).json({ error: "internal server error" });
});
app.listen(port, "127.0.0.1", () => {
console.log(`listening on 127.0.0.1:${port}`);
});
Express는 app.use와 라우트를 등록한 순서대로 실행합니다. 이 앱에서는 순서마다 이유가 있습니다.
| 순서 | 등록한 것 | 이 자리에 두는 이유 |
|---|---|---|
| 1 | logger |
맨 앞에 있어야 400, 404, 500으로 끝난 요청도 기록 |
| 2 | express.json() |
라우트보다 앞에 있어야 req.body가 채워짐 |
| 3 | /todos 라우터 |
실제 처리 |
| 4 | 404 처리 | 앞의 라우트가 응답하지 않은 요청만 도달 |
| 5 | 에러 처리 미들웨어 | 앞에서 던진 에러를 받도록 맨 뒤에 배치 |
서버를 실행합니다.
node app.js 4201
listening on 127.0.0.1:4201
5. GET, POST, PUT, DELETE 호출
다른 터미널에서 목록을 조회합니다. -i는 응답 헤더까지 출력하는 옵션입니다.
curl -i http://127.0.0.1:4201/todos
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 93
ETag: W/"5d-nqdxvbtaF5XXPe9pskRWF/lqCek"
Date: Mon, 16 Nov 2026 08:49:44 GMT
Connection: keep-alive
Keep-Alive: timeout=5
[{"id":1,"title":"install express","done":true},{"id":2,"title":"split router","done":false}]
res.json()이 Content-Type: application/json을 붙였습니다. 아래부터는 X-Powered-By, Content-Length, ETag, Date, Connection, Keep-Alive 줄을 빼고 싣습니다.
한 건 조회입니다.
curl -i http://127.0.0.1:4201/todos/2
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"id":2,"title":"split router","done":false}
POST로 새 항목을 만듭니다. 본문이 JSON이라는 것을 Content-Type 헤더로 알려야 express.json()이 읽습니다.
curl -i -X POST http://127.0.0.1:4201/todos \
-H "Content-Type: application/json" \
-d '{"title":"check with curl"}'
HTTP/1.1 201 Created
Location: /todos/3
Content-Type: application/json; charset=utf-8
{"id":3,"title":"check with curl","done":false}
새로 만들었으므로 200이 아니라 201 Created이고, Location 헤더가 새 항목의 주소를 알려 줍니다.
PUT으로 2번 항목을 통째로 바꿉니다.
curl -i -X PUT http://127.0.0.1:4201/todos/2 \
-H "Content-Type: application/json" \
-d '{"title":"split router","done":true}'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"id":2,"title":"split router","done":true}
DELETE로 1번 항목을 지웁니다.
curl -i -X DELETE http://127.0.0.1:4201/todos/1
HTTP/1.1 204 No Content
204는 성공했고 돌려줄 본문이 없다는 뜻입니다. 목록을 다시 조회하면 세 요청의 결과가 모두 반영되어 있습니다.
curl -i http://127.0.0.1:4201/todos
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
[{"id":2,"title":"split router","done":true},{"id":3,"title":"check with curl","done":false}]
6. 잘못된 요청: 400, 404, 500
정상 요청만 확인하면 절반만 본 셈입니다. 틀린 입력을 보내 서버가 어떤 상태 코드로 답하는지 봅니다.
빈 제목은 validateBody가 거절합니다.
curl -i -X POST http://127.0.0.1:4201/todos \
-H "Content-Type: application/json" \
-d '{"title":""}'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"title must be a non-empty string"}
done에 문자열을 넣어도 거절됩니다. 값이 있는지만 보지 않고 타입까지 확인하기 때문입니다.
curl -i -X POST http://127.0.0.1:4201/todos \
-H "Content-Type: application/json" \
-d '{"title":"x","done":"yes"}'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"done must be a boolean"}
숫자가 아닌 id와 없는 id는 router.param에서 서로 다른 코드로 갈립니다.
curl -i http://127.0.0.1:4201/todos/abc
curl -i http://127.0.0.1:4201/todos/99
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"id must be a positive integer"}
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{"error":"todo not found"}
깨진 JSON을 보내면 라우트에 닿기 전에 express.json()이 에러를 던집니다. 이 에러는 맨 뒤의 에러 처리 미들웨어가 받아 400으로 바꿉니다.
curl -i -X POST http://127.0.0.1:4201/todos \
-H "Content-Type: application/json" \
-d '{"title":'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"invalid JSON body"}
등록하지 않은 경로는 404 처리 미들웨어까지 내려갑니다.
curl -i http://127.0.0.1:4201/users
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{"error":"not found","path":"/users"}
마지막으로 handler 안에서 에러가 나는 경우입니다. /todos/boom은 일부러 throw합니다.
curl -i http://127.0.0.1:4201/todos/boom
HTTP/1.1 500 Internal Server Error
Content-Type: application/json; charset=utf-8
{"error":"internal server error"}
응답에는 demo failure라는 에러 메시지가 없습니다. 메시지와 스택은 서버 콘솔에만 남기고, 클라이언트에는 고정된 문구만 보냅니다. 에러 처리 미들웨어를 직접 등록하지 않으면 Express 기본 처리기가 응답합니다. 기본 처리기로 같은 에러를 받아 보니 NODE_ENV를 정하지 않았을 때는 파일 경로가 담긴 스택이 HTML 본문에 그대로 나왔습니다. NODE_ENV=production에서는 Internal Server Error 한 줄로 줄어듭니다.
서버 터미널에는 로깅 미들웨어가 남긴 기록이 요청 순서대로 쌓여 있습니다.
listening on 127.0.0.1:4201
GET /todos 200 4ms
GET /todos/2 200 1ms
POST /todos 201 14ms
PUT /todos/2 200 1ms
DELETE /todos/1 204 0ms
GET /todos 200 1ms
POST /todos 400 1ms
POST /todos 400 1ms
GET /todos/abc 400 0ms
GET /todos/99 404 1ms
POST /todos 400 2ms
GET /users 404 0ms
unhandled: demo failure
GET /todos/boom 500 1ms
7. 자주 막히는 두 가지
Content-Type 헤더를 빼고 POST를 보내면 본문이 있어도 400이 나옵니다.
curl -i -X POST http://127.0.0.1:4201/todos -d 'title=form'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"title must be a non-empty string"}
curl -d는 기본으로 application/x-www-form-urlencoded를 붙입니다. express.json()은 JSON이 아닌 본문을 읽지 않으므로 req.body에 title이 없습니다.
Windows에서 -d 인자에 한글을 직접 쓰면 글자가 깨져서 전달됩니다. -d '{"title":"curl로 확인"}'을 보냈을 때 저장된 값은 curl? ??였습니다. 본문을 UTF-8 파일로 저장하고 @파일로 보내면 그대로 들어갑니다.
curl -i -X POST http://127.0.0.1:4201/todos \
-H "Content-Type: application/json" \
--data-binary @body-ko.json
HTTP/1.1 201 Created
Location: /todos/4
Content-Type: application/json; charset=utf-8
{"id":4,"title":"한글 제목","done":false}
body-ko.json의 내용은 {"title":"한글 제목"} 한 줄입니다.
8. 요청과 응답 정리
| 요청 | 상태 코드 | 응답을 만든 곳 |
|---|---|---|
GET /todos |
200 | 라우터 |
GET /todos/2 |
200 | 라우터 |
POST /todos (정상) |
201 | 라우터 |
PUT /todos/2 |
200 | 라우터 |
DELETE /todos/1 |
204 | 라우터 |
POST /todos (빈 제목, 틀린 타입) |
400 | validateBody |
GET /todos/abc |
400 | router.param |
GET /todos/99 |
404 | router.param |
POST /todos (깨진 JSON) |
400 | 에러 처리 미들웨어 |
GET /users |
404 | 404 처리 미들웨어 |
GET /todos/boom |
500 | 에러 처리 미들웨어 |
첫 응답에 있던 X-Powered-By: Express는 서버 종류를 알려 주는 헤더입니다. 이 헤더를 지우고 보안 헤더를 붙이는 방법은 Express helmet 적용 전후 비교 글에 있습니다.
이 API의 데이터는 메모리에만 있어서 서버를 다시 시작하면 처음 두 항목으로 돌아갑니다. 인증도 없으므로 누구나 지울 수 있습니다. 구조를 익힌 뒤에는 저장소와 인증을 붙여야 실제 서비스에 쓸 수 있습니다.
자주 묻는 질문
미들웨어 등록 순서가 왜 중요합니까?
Express는 등록한 순서대로 실행하므로, express.json()이 라우트보다 뒤에 있으면 req.body가 비어 있고 에러 처리 미들웨어가 앞에 있으면 에러를 받지 못합니다.
app.use와 app.get은 무엇이 다릅니까?
app.use는 메서드와 상관없이 경로의 앞부분이 맞으면 실행되고, app.get은 GET 요청이면서 경로 전체가 맞을 때만 실행됩니다.
async handler 안에서 난 에러도 에러 처리 미들웨어로 갑니까?
가지 않습니다. Express 4.21.2에서 async handler가 throw하자 서버 프로세스가 종료 코드 1로 끝났으므로, try와 catch로 받아 next(err)를 직접 불러야 합니다.
이 글의 다음 단계
- Express helmet 보안 헤더: 적용 전후 응답 비교같은 Express 앱을 helmet 없이 실행했을 때와 helmet을 적용했을 때 HTTP 응답 헤더가 어떻게 달라지는지 curl 출력으로 비교합니다. 헤더가 무엇을 막는지, 어디서 확인하는지, 적용할 때 주의할 점까지 정리합니다.
- React XSS 점검: dangerouslySetInnerHTML과 사용자 입력 렌더링같은 댓글 입력을 React 기본 렌더링과 dangerouslySetInnerHTML로 각각 그려 보고, 스크립트 실행 여부를 헤드리스 Chromium으로 확인합니다. 위험한 코드를 찾는 방법과 안전한 기본 형태를 정리합니다.
이 내용을 팀 교육으로 진행하고 싶으신가요?
인원, 수준, 일정에 맞춰 실습 환경까지 준비해 진행합니다. 대상과 기간을 알려 주시면 구성을 제안해 드립니다.
교육 문의하기메일로 보내실 수도 있습니다: fankh111@gmail.com