Web/Node.js

[Node.js] 웹 서버 구현

devsalix 2022. 12. 12. 13:40
728x90

우선 웹 서버 구조는

 

아래와 같이 구성하고

 

  • [파일] index.js
  • [폴더] public
    • [파일] index.html
    • [파일] error.html

 

그리고 웹 서버를 구현하기 위해서는

 

express 모듈과 ejs 뷰 엔진이 필요합니다

 

VS Code 에서 새 터미널을 연 상태로

 

터미널에서

 

> npm install express

 

그리고

 

> npm install ejs

 

를 입력하여 express와 ejs를 설치해 줍니다

 

상위 폴더에 index.js 파일에 해당 구문을 입력해 줍니다

 

const express = require('express');
const app = express();
const port = 80;

app.set('views', __dirname + '/public');
app.set('view engine' , 'ejs');
app.engine('html', require('ejs').renderFile);

app.use('/', express.static(__dirname + '/public/'));

app.use(function(req, res, next){
    res.status(404).render(__dirname + '/public/error.html');
})

app.listen(port, function(){
    console.log("서버 구동 완료!!");
});

 

이후 터미널에서

 

> node index.js

 

입력하면 "서버 구동 완료!!" 문구가 뜨면서 대기하게 됩니다

 

public 폴더 하단 index.html 은 아래와 같이 작성합니다

 

<!DOCTYPE html>
<html lang="ko-kr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
</head>
<body>
    <h1>환영 합니다!!!</h1>
</body>
</html>

 

그리고 error.html 은 아래와 같이 작성합니다

 

<!DOCTYPE html>
<html lang="ko-kr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error</title>
</head>
<body>
    <h1>페이지가 존재하지 않습니다!!</h1>
</body>
</html>

 

이후 인터넷 창에서 주소를 localhost 로 입력하면

 

public 폴더 하위 index.html이 출력됩니다

 

만약 없는 페이지로 접근을 하게 되면

 

public 폴더 하위 error.html 파일을 출력합니다

 

 


제 글이 도움이 되셨다면 댓글 & 공감 부탁드려요 😀

 

 
728x90
반응형