-
노드 express로 html 서빙하기노드 2023. 4. 17. 15:59
express로 만든 서버에 html 파일을 서빙해보자.
이 전 게시글에 있었던 코드는 다음과 같다
//app.js const express = require('express'); const path = require('path'); const app = express(); app.set('port', process.env.PORT || 3000); app.get('/', (req, res) => { //res.send('Hello, Express'); res.sendFile(path.join(__dirname, '/index.html')); }); app.listen(app.get('port'), () => { console.log(app.get('port'), '번 포트에서 대기 중'); });
//index.html <html> <head> <meta charset="UTF-8" /> <title>익스프레스 서버</title> </head> <body> <h1>익스프레스</h1> <p>배워봅시다.</p> </body> </html>
html 파일을 보낼 것이기 때문에 index.html 파일을 만들었다.
app.js 코드에서 sendFile을 사용하면 자동으로 fs 모듈을 사용하여 파일을 읽어온다.
node app 해서 서버를 실행하고 브라우저에서 localhost:3000하면 성공적으로 html파일을 서빙한 것을 볼 수 있다.
'노드' 카테고리의 다른 글
노드 미들웨어 특성 이해하기 (0) 2023.04.17 노드 미들웨어 사용하기 (0) 2023.04.17 노드 Express 웹 서버 시작하기 (0) 2023.04.17 npm 배포하기 (0) 2023.04.14 노드 npm 명령어 (1) 2023.04.14