ํฐ์คํ ๋ฆฌ ๋ทฐ
[ node.js ] html ํ์ผ ์ฝ์ด๋ค์ฌ ์๋ตํ๊ธฐ( with serve-static)
Kithub 2020. 3. 31. 23:46ํ๋ก์ ํธ ๊ตฌ์กฐ
index.html
ํด๋ผ์ด์ธํธ๊ฐ ๋ก๊ทธ์ธ์ ์ํํ ํ์ด์ง ์ ๋๋ค.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>kithub page</title>
</head>
<body>
<h1>This is login page</h1>
<form>
์์ด๋ : <input type="text" name="id"><br/>
๋น๋ฐ๋ฒํธ : <input type="password" name="pwd">
<button>๋ก๊ทธ์ธ</button>
</form>
</body>
</html>
kithubServer.js
์น์๋ฒ๊ฐ ๋ js ํ์ผ์ ๋๋ค.
๊ตฌ์ฑ ๋ชจ๋ :
path : ํ์ผ ๋ฐ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก์ ๊ด๋ จ๋ ๋ชจ๋
static : ํน์ ํด๋์ ํ์ผ๋ค์ ํน์ ํจ์ค๋ก ์ ๊ทผํ ์ ์๋๋ก ํด์ฃผ๋ ๋ฏธ๋ค์จ์ด
var express = require('express')
, http = require('http')
, path = require('path')
, static = require('serve-static');
var app = express();
app.use('/',static(path.join(__dirname,'html')));
http.createServer(app).listen(3001,function(){
console.log('express webserver start ! :: 3001');
})
ํด๋ผ์ด์ธํธ๋ก๋ถํฐ ์์ฒญ์ด ๋ค์ด์์ ์ html ํ์ผ์ ์ฝ์ด๋ค์ด๊ธฐ ์ํ ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
app.use('/html', static(path.join(__dirname,'html')));
์ฒซ๋ฒ์งธ ์ธ์ :
'/html'์ html ํด๋์์ ์๋ index.html์ ์์ฒญํ๊ธฐ ์ํ ์์ฒญ๋ฃจํธ๋ฅผ ์ง์ ํด์ค๋๋ค.
๋๋ฒ์งธ ์ธ์ :
__dirname์ ๋ฃจํธ ๊ฒฝ๋ก์ ๋๋ค.
์ค์ ๋ก ์๋ฒํ์ผ์ ์์น๋ C:\nodejs\kithub ์ ์ด๊ณ , __dirname๋ฅผ ์ฝ์๋ก ์ฐ์ด๋ณด๋ฉด C:\nodejs\kithub ๊ฒฝ๋ก๊ฐ ์ฐํ๋ ๊ฒ์ ํ์ธ ํ ์ ์์ต๋๋ค.
'html'์ ์ฐพ๊ณ ์ ํ๋ ํด๋์ ์ด๋ฆ ์ ๋๋ค.
์์์ ์ธ๊ธ๋ ํ๋ก์ ํธ์ ๊ตฌ์กฐ๋ฅผ ๋ณด๋ฉด kithub/html/index.html ์ ๊ตฌ์กฐ๋ผ๋๊ฑธ ํ์ธ ํ ์ ์๋๋ฐ์.
index.html์ด ์์นํด ์๋ ์์ ํด๋๋ช (html)์ ๊ธฐ์ค์ผ๋ก ์ํ๋ ํ์ผ์ ์ ๊ทผ์ ํ๊ฒ ๋ฉ๋๋ค.
์ฆ,
์ฒซ๋ฒ์งธ ์ธ์๋ ์์ฒญํจ์ค , ๋๋ฒ์งธ ์ธ์๋ static() ๋ฉ์๋๋ก ํน์ ํด๋๋ฅผ ์ง์ ํด์ฃผ์์ต๋๋ค.
๊ทธ๋ผ ์ด์
์น์๋ฒ๋ฅผ ์คํ ์ํค๊ณ 'http://localhost:3001/html/'
๋ค์ ์ฃผ์๋ก ์ ๊ทผํ๋ฉด index ํ์ด์ง๊ฐ ์ ์์ ์ผ๋ก ํธ์ถ๋๋ ๊ฒ์ ํ์ธ ํ ์ ์์ต๋๋ค.