🧱 Framework/Node.js

express static, μ •μ νŒŒμΌ μ „λ‹¬ν•˜κΈ°

jaeyunim 2023. 3. 22. 15:37

정적 νŒŒμΌμ΄λž€?

λ³€ν™”ν•˜μ§€ μ•ŠλŠ” 파일. image, css, js파일 등을 μ˜λ―Έν•œλ‹€.

 

expressμ—μ„œλŠ” 정적 νŒŒμΌμ„ μ‰½κ²Œ 전달할 수 μžˆλŠ” κΈ°λŠ₯을 κ°€μ§€κ³  μžˆλ‹€.


express.static()

express.static 미듀웨어에 ν¬ν•¨μ‹œν‚€λ©° μ „λ‹¬ν•˜λ©΄, 파일의 직접적인 μ œκ³΅μ„ μ‹œμž‘ν•  수 μžˆλ‹€.

app.use(expres.static('public'));

 

 

μœ„μ™€ 같이 μž‘μ„±ν–ˆλ‹€λ©΄

 

λ‹€μŒκ³Ό 같은 μ£Όμ†Œλ‘œ public 디렉토리에 ν¬ν•¨λœ νŒŒμΌμ„ λ‘œλ“œν•  수 μžˆλ‹€.

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

가상 경둜λ₯Ό μž‘μ„±ν•˜κ³  싢은 경우

λ‹€μŒκ³Ό 같은 ν˜•μ‹μœΌλ‘œ μž‘μ„±ν•˜λ©΄ λœλ‹€.

app.use('/static', express.static('public'));

/static 접두뢀λ₯Ό 톡해 public 디렉토리에 ν¬ν•¨λœ νŒŒμΌμ„ λ‘œλ“œνž 수 μžˆλ‹€.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

μ ˆλŒ€ 경둜의 μ‚¬μš©

express.static ν•¨μˆ˜μ— μ œκ³΅λ˜λŠ” κ²½λ‘œλŠ”, node ν”„λ‘œμ„ΈμŠ€κ°€ μ‹€ν–‰λ˜λŠ” 디렉토리에 λŒ€ν•΄ μƒλŒ€μ μ΄λ‹€.

 

λ”°λΌμ„œ __dirname κ³Ό 같은 μ ˆλŒ€ 경둜λ₯Ό μ‚¬μš©ν•˜λŠ” 것이 μ•ˆμ „ν•˜λ‹€.

 

"dir__name"은 ν˜„μž¬ μ‹€ν–‰ 쀑인 ν΄λ”μ˜ 경둜λ₯Ό λœ»ν•œλ‹€.

app.use('/static', express.static(__dirname + '/public'));

μ˜ˆμ‹œ

server.js 에 λ‹€μŒ μ½”λ“œλ₯Ό μž‘μ„±

app.use("/public", express.static(__dirname + "/public"));

 

app.js

 

이러면 μ•„λž˜μ™€ 같이 μ •μ νŒŒμΌμ΄ localhost:4000/public/js/app.js μ£Όμ†Œλ‘œ μ „λ‹¬λœλ‹€.