자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Express] 4장 정적 파일 제공

728x90

1.Express.static()

express.static()은 Express에서 이미지, CSS, JS 같은 정적 파일을 클라이언트에 직접 서빙하기 위해 쓰는 기본 미들웨어로 브라우저가 /images/logo.png 같은 경로로 요청하면, 서버가 코드를 따로 실행하지 않고 해당 파일을 그대로 반환 해 줍니다.

const express = require("express");
const path = require("path");
const app = express();
const port = 3000;

// public 폴더를 정적 파일 경로로 지정함
app.use(express.static(path.join(__dirname, "public")));

app.listen(3000, () => {
  console.log(`Server is running port ${port}`);
});

✅ 2. 폴더 구조 예시

project/
 ├─ server.js
 └─ public/
     ├─ images/
     │    └─ logo.png
     ├─ css/
     │    └─ style.css
     └─ js/
          └─ app.js

 

🚀 브라우저 접근 방법

  • http://localhost:3000/images/logo.png
  • http://localhost:3000/css/style.css
  • http://localhost:3000/js/app.js

✅ 3. 경로 프리픽스 붙이기

URL 경로 앞에 접두어를 붙이려면 다음과 같습니다.

app.use(express.static(path.join(__dirname, "public")));

 

이제 부라우저는 다음 URL로 접근 가능합니다.

  • http://localhost:3000/static/images/logo.png

🚨 주의 사항

  • 보안:  민감한 정보(비밀번호, DB 설정 파일 등)는 정적 폴더 X
  • 캐싱express.json()는 기본적으로 브라우저 캐싱이 지원되며, 파일 변경시 브라우저 캐시를 무효화 시켜야함
  • 순서express.static()는 라우터보다 먼저 설정해야 정적 파일이 잘 서빙

4. 전체 예제

  • server.js
const express = require("express");
const path = require("path");
const app = express();
const port = 3000;

// public 폴더를 정적 파일 경로로 지정함
app.use(express.static(path.join(__dirname, "public")));

app.listen(3000, () => {
  console.log(`Server is running port ${port}`);
});
  • index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>정적 파일 테스트</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <div class="Timer">
      <div>
        <h1>Hello Express!</h1>
        <h2>🕝 Time</h2>
        <p id="timer">0Sec</p>
      </div>
      <script src="./js//app.js"></script>
    </div>
  </body>
</html>
  • css/style.css
body {
  font-family: sans-serif;
  background: darkorange;
  padding-top: 50px;
}

.Timer {
  display: flex;
  justify-content: center;
  height: 500px;
  align-items: center;
}

.Timer div {
  color: #fff;
}
  • js/app.js
let seconds = 0;
const timerElement = document.getElementById("timer");

function formatTime(sec) {
  const hrs = String(Math.floor(sec / 3600)).padStart(2, "0");
  const mins = String(Math.floor((sec % 3600) / 60)).padStart(2, "0");
  const secs = String(sec % 60).padStart(2, "0");
  return `${hrs}:${mins}:${secs} 초`;
}

timerElement.textContent = formatTime(seconds);

setInterval(() => {
  seconds++;
  timerElement.textContent = formatTime(seconds);
}, 1000);

5. 서버 실행

node server.js

 

브라우저 http://localhost:3000에 접속해 타이머가 작동되는 것을 볼 수 있습니다.


 

 

GitHub - Koras02/express-bloging: https://thinky.tistory.com/category/Back-End/Express

https://thinky.tistory.com/category/Back-End/Express - Koras02/express-bloging

github.com

 

728x90
LIST

'Back-End > Express' 카테고리의 다른 글

[Express] 6장 라우터 분리  (0) 2025.09.06
[Express] 5장 에러 처리  (1) 2025.08.22
[Express] 3장 - 미들웨어 적용  (1) 2025.08.13
[Express] 2장 - 라우팅 구현  (4) 2025.08.11
[Express] 1장 Express란 무엇인가  (3) 2025.08.10