오늘은 Node.js와 Express.js를 활용하여 간단한 서버를 구축하는 방법을 학습했다.
Express.js는 Node.js 환경에서 웹 서버를 쉽게 구축할 수 있게 해주는 프레임워크로, 간결한 코드만으로 서버 기능을 구현할 수 있다.
Express 서버 기본 설정
const express = require("express");
const path = require("path");
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log("START SERVER");
})
express와 path 모듈을 불러와 app 인스턴스를 생성하고, 포트 번호를 3000으로 설정하여 서버 리스닝을 시작한다.
정적 파일 제공 설정
// 프로젝트 루트 디렉토리 기준
app.use(express.static(path.join(__dirname, "..")));
express.static 미들웨어를 사용해 클라이언트에 정적 파일(HTML, CSS, JS 등)을 제공한다. 상대 경로 설정을 위해 path.join(__dirname, "..")을 활용한다.
SPA 라우팅 처리
// 모든 경로에 대해 index.html 반환
app.get("/*", (_, res) => {
res.sendFile(path.join(__dirname, "..", "index.html"));
});
클라이언트 측 라우팅을 가진 SPA가 정상적으로 작동하도록 모든 경로(/*)에 대해 index.html을 반환하도록 설정한다.
완성된 코드
완성된 코드를 server/server.js 파일에 저장한다.
// server.js
const express = require("express");
const path = require("path");
const app = express();
const PORT = 3000;
app.use(express.static(path.join(__dirname, "..")));
app.get("/*", (_, res) => {
res.sendFile(path.join(__dirname, "..", "index.html"));
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
터미널에서 다음 명령어를 실행하면 서버가 구동된다.
node ./server/server.js
이제 브라우저에서 http://localhost:3000으로 접속하면 SPA가 정상적으로 동작하는지 확인할 수 있다.
'TIL' 카테고리의 다른 글
| 적절한 함수명과 단일 책임으로 코드 개선하기 (0) | 2025.11.13 |
|---|---|
| 상태 관리 설계 (0) | 2025.11.10 |
| 컴포넌트와 모듈 시스템 (0) | 2025.11.10 |
| JavaScript의 this와 MPA 구현 (0) | 2025.11.10 |
| innterHTML, innerText, textContent의 차이 (0) | 2025.11.10 |
