본문 바로가기
Web/Node.js

07. http 모듈, 템플릿 엔진

by 사라리24 2024. 4. 24.
SMALL

1. http 모듈

 웹 서버와 클라이언트를 만들고 관리하는데 사용되는 핵심 모듈
 HTTP 서버를 만들거나 HTTP 클라이언트 요청을 만들 수 있음

 

  • HTTP 서버를 생성_요청에 따라 파일을 제공
  
       < js >

 
            const http=require('http');
            const fs=require('fs');

            console.log('http 모듈 테스트');
            console.log('노드몬이 실행중입니다!');

            //req:request(사용자가 전달한 객체)
            //res:response(사용자가 전달받을(사용자에게 전달할)객체)
            const server=http.createServer((req,res)=>{
                console.log('server가 동작중입니다.');
                console.log(req.headers);
                console.log(req.method);    // 전송방법
                console.log(req.url);
 
            if(url==='/'){  
                //url에 /이 있다면 ./html/index.html이 나옴
                //pipe(res:) 사용자에게 전달
                fs.createReadStream('./page/index.html').pipe(res);
            }else if(url==='/mypage'){  
                // url에 /mypage이 있다면 ./html/news.html이 나옴
                fs.createReadStream('./html/mypage.html').pipe(res);
            }else{  
                // 나머지 경우 ./html/not-found.html이 나옴
                fs.createReadStream('./html/not-found.html').pipe(res);
            }
 
 
            });

            //localhost:8080
            server.listen(8080);
 
       </js >
  
[terminal 창]
http 모듈 테스트
노드몬이 실행중입니다!

[ 브라우저에 localhost:8080 입력]
server가 동작중입니다.
{
  host: 'localhost:8080',
  connection: 'keep-alive',
  'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': '"Windows"',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  'sec-fetch-site': 'none',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-user': '?1',
  'sec-fetch-dest': 'document',
  'accept-encoding': 'gzip, deflate, br, zstd',
  'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7'
}
GET
/

  1. http와 fs 모듈을 가져옵니다.
  2. 콘솔에 'http 모듈 테스트'와 '노드몬이 실행중입니다!'를 출력합니다.
  3. createServer 함수를 사용하여 HTTP 서버를 생성합니다. 이 서버는 요청(req)과 응답(res)을 처리하는 콜백 함수를 인자로 받습니다.
  4. 요청에 대한 처리를 위해 콜백 함수 내에서 다음을 수행합니다:
    • 요청 헤더를 콘솔에 출력합니다.
    • 요청 메소드(GET, POST 등)를 콘솔에 출력합니다.
    • 요청 URL을 콘솔에 출력합니다.
    • URL이 '/'일 경우, './page/index.html' 파일을 스트리밍하여 응답으로 전송합니다.
    • URL이 '/mypage'일 경우, './html/mypage.html' 파일을 스트리밍하여 응답으로 전송합니다.
    • 그 외의 경우, './html/not-found.html' 파일을 스트리밍하여 응답으로 전송합니다.

 

📌package.json 만들기

터미널창에 아래 문구 입력


npm init

npm init -y (기본값을 생성)


📌nodemon 설치


npm i nodemon --save-dev        -> 이건 저장하면 바로 터미널창에서 실행되게 해줌. 개발할 때 유용



npm i nodemon --save-dev 를 터미널에 입력하여 설치한 후 package.json에 들어가 debug 아래에 위치한

"scripts": {

    "test": "echo \"Error: no test specified\" && exit 1",

    "start":"nodemon 4-http",

    "mzgz": "node 4-http"

  } -> 패키지 스크립트 부분에 start, mzgz 한 줄 씩 추가 (여기서 4-http는 만든 js 파일의 이름. 4-http.js)


  npm run mzgz: 터미널창에 위 문구를 입력하면 4-http 파일이 터미널에서 출력 -> 약간 불편하다

 📌 npm start: 이걸 쓰면 터미널이 끝나지 않고 계속 대기, 
저장하면 바로 출력 ->nodemon을 이용했다. 
이를 통해 ctrl+s로 편하게 결과를 확인할 수 있다.

 

 

2. 템플릿 엔진

웹 어플리케이션에서 동적으로 HTML을 생서하는데 사용하는 도구 및 라이브러라
HTML 페이지 내에서 데이터를 동적으로 삽입하고 조작하는데 도움이 되며,
주로 웹 어플리케이션 뷰 부분을 생성하는데 활용
- EJS. Pug, Handlebars, Nunjucks ....

 

 

EJS -- Embedded JavaScript templates

Simple syntax JavaScript code in simple, straightforward scriptlet tags. Just write JavaScript that emits the HTML you want, and get the job done!

ejs.co

 

  • 설치하기
    terminal 창에 nmp i ejs 입력

package.json 에서 설치확인
템플릿 파일 index -> ejs 로 변경

 

  • 문제
    / index와 /news 외의 모든 페이지를 not-found.ejs로 만들어 출력하기
    단. not-found.ejs에 전달할 매개변수는 userid:apple, name:'김사과'로 함

    출력예시
    apple(김사과)님이 요청하신 페이지가 없어요! 😋😎🤣
 
      < js >

             const http=require('http');
             const fs=require('fs');
             const ejs=require('ejs');
             // npm i ejs: 터미널창에 입력 설치

             const name='김사과';
             const userid='apple';

             const jobs = [
                 {job:'학생'},
                 {job:'개발자'},
                 {job:'교사'},
                 {job:'공무원'},
                 {job:'취준생'}
             ];

             // template 폴더 만들고 파일들의 확장자 바꿔주기
             const server = http.createServer((reqres=> {
                 const url = req.url;
                 res.setHeader('Content-Type''text/html');
                 if(url === '/'){
                     ejs.renderFile('./template/index.ejs', {name:name})
                     .then((data=> res.end(data));

       </js >
  





 

         
      < js >

              }else if(url === '/news'){
                  ejs.renderFile('./template/news.ejs', {jobs:jobs})
                  .then((data=> res.end(data));
 
       </js >
  
 



 
      < js >
           
                }else{
                    ejs.renderFile('./template/not-found.ejs', {userid:useridname:name})
                  .then((data)=>res.end(data));
                }
            });
 
             server.listen(8080);

       </js >
  



 

 

2. REST(Representational State Transfer)

  자원을 이름을 구분하여 해당 자원의 상태를 주고 받는 것을 의미

 

  • REST API
    REST 기반으로 서비스 API를 구현한 것
  • API (Application Programing Interface)
    기능의 집합을 제공해서 컴퓨터 프로그램의 상호작용을 하도록 하는것

 

  • CRUD
    POST: 생성(create)
    GET: 조회(read)
    PUT: 수정(upate)
    DELETE: 삭제(delete)
  
       < js >

            const http = require('http');
            const skills=[
                {name:'Python'},
                {name:'MySQL'},
                {name:'HTML'},
                {name:'CSS'},
                {name:'JavaScript'}
            ]
            const server = http.createServer((req,res)=>{
                const url = req.url;
                const method = req.method;
                if(method === 'GET'){
                    // res.setHeader('Content-Type','text/html');
                    // 2XX: 정상적인 호출, 4XX: 잘못된 페이지 호출(ex:404), 5XX: 서버 오류
                    res.writeHead(200, {'Content-Type':'application/json'});
                    res.end(JSON.stringify(skills));
                }
            });
            server.listen(8080);

 
       </js >
  
[package.json]
"start":"nodemon 6_rest

[terminal]
 npm start

 

 

'Web > Node.js' 카테고리의 다른 글

09. git 설치, github 간단 연동  (0) 2024.04.25
08. Express 웹 프레임워크, route, morgan  (0) 2024.04.25
06. 버퍼(buffer), 스트림(Steam)  (0) 2024.04.24
05. Console, This, file  (0) 2024.04.23
04. JSON  (0) 2024.04.23