๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Node.js

[Node.js] express์—์„œ html ์‚ฌ์šฉํ•˜๊ธฐ | ๋ Œ๋”๋ง ํ•˜๊ธฐ

728x90

 

๐Ÿ˜Ž express์—์„œ html  ์‚ฌ์šฉํ•˜๊ธฐ

 

1. ๋‚ด๊ฐ€ ์›ํ•˜๋Š” url๋กœ html์„ ๊ฐ€์ ธ์˜ค๊ณ  ์‹ถ์„ ๋•Œ (ejs ์‚ฌ์šฉํ•ด์„œ ๋ Œ๋”๋ง)

 

ํ„ฐ๋ฏธ๋„์—์„œ ๋จผ์ € npm i ejs๋ฅผ ๊น”์•„์ค˜์•ผํ•œ๋‹ค.

npm i ejs

์›ํ•˜๋Š” url ์ฃผ์†Œ๋กœ ๋ Œ๋”๋งํ•˜๊ธฐ ์œ„ํ•ด์„œ ejs๋ฅผ ์‚ฌ์šฉํ•ด์„œ html์„ ์ฝ์–ด์˜จ๋‹ค.
-> get("/์›ํ•˜๋Š” ์ฃผ์†Œ")์œผ๋กœ ์›ํ•˜๋Š” url๋กœ ๋ Œ๋”๋งํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.

app.set('view engine', 'ejs'); // ejs๋กœ html ๋ Œ๋”๋ง
app.engine('html', require('ejs').renderFile);

app.get("/test", (req, res) => {
    res.render("index.html")
})

์š”์ฒญ ๋ณด๋‚ผ ๋•Œ ์ด๋ ‡๊ฒŒ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋‹ค.

http://localhost:5000/test

 

 

2. ์ฃผ์†Œ ๋’ค์— /index.html(ํŒŒ์ผ์ด๋ฆ„)์œผ๋กœ ์จ์„œ ์‚ฌ์šฉํ•  ๋•Œ (express์—์„œ ์ œ๊ณตํ•˜๋Š” static ์‚ฌ์šฉ)

 

1. ๊ธฐ๋ณธ ์‚ฌ์šฉ

public์ด๋ผ๋Š” ํด๋” ์•ˆ์— ์žˆ๋Š” ํŒŒ์ผ์„ ์ฝ์–ด์˜จ๋‹ค๋Š” ๋œป์ด๋‹ค.

์ด๋ ‡๊ฒŒ ์จ์ฃผ๋ฉด public ํด๋” ์•ˆ์— ์žˆ๋Š” ๊ฒƒ์€ url/"ํŒŒ์ผ์ด๋ฆ„" ์„ ์จ์„œ ์š”์ฒญ์„ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

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

์š”์ฒญ ๋ณด๋‚ผ ๋•Œ ์ด๋ ‡๊ฒŒ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋‹ค.

http://localhost:5000/index.html

 

2. ์›ํ•˜๋Š” ์ฃผ์†Œ + index.html

app.use('/static', express.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 ๊ณต์‹๋ฌธ์„œ์—์„œ ๋ณด๊ธฐ

-> http://expressjs.com/ko/starter/static-files.html#express%EC%97%90%EC%84%9C-%EC%A0%95%EC%A0%81-%ED%8C%8C%EC%9D%BC-%EC%A0%9C%EA%B3%B5

 

 

 

 

 

 

728x90