express static, μ μ νμΌ μ λ¬νκΈ°
μ μ νμΌμ΄λ?
λ³ννμ§ μλ νμΌ. 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 μ£Όμλ‘ μ λ¬λλ€.