๐ 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 ๊ณต์๋ฌธ์์์ ๋ณด๊ธฐ
'Node.js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Node.js] ๋ ธ๋๋ ๋ฌด์์ธ๊ฐ? (0) | 2022.04.13 |
---|---|
[Node.js] Request log ๋จ๊ธฐ๋ ๋ฏธ๋ค์จ์ด (0) | 2022.03.21 |
[Node.js] ๋ ธ๋ Restful API ๋ ๋ฌด์์ผ๊น? (0) | 2022.01.31 |
[Node.js] ๋ ธ๋ package.json ์ฌ์ฉ๋ฒ (1) | 2022.01.31 |
[Node.js] Express ์ค์นํ๊ธฐ | ๋ ธ๋js ํ๋ ์์ํฌ ์ฌ์ฉํ๊ธฐ (0) | 2022.01.29 |