[Node.js] 미들웨어1 활용

Posted by 신희준 on November 8, 2017


모덴웹을 위한 Javascript, JQuery입문 [윤인성 지음] 참고


2017 - 11 - 08 (수)

  • static 미들웨어
  • route 미들웨어

  • static 미들웨어


    • 정적 파일 제공


    static 미들웨어란 예를들어 어떤 포털페이지에 접속하여 계속해서 새로고침했을 때 실시간 검색순위가 바뀌는 것을 볼 수 있다. 이러한 부분처럼 요청할 때마다 다이내믹한 반응을 보이는 부분을 동적파일이라고 부른다.


    하지만 이러한 부분과 달리 계속 요청해도 같은 부분이 있다. 이런 부분을 정적 파일이라고 한다. static 미들웨아를 통해 이러한 정적 파일을 관리해줄 수 있다.


    프로젝트 폴더에 우선 public 이라는 폴더를 하나 생성하고 index.html 파일을 이동시킨다.

     var express =require('express');
    
     var app = express();
    app.use(express.static('public'));
    // localhost에 접속했을 때 public 폴더의 index.html을 실행시킨다.
    



    라우터 미들웨어


    사용자의 요청에 따라 사용자가 필요한 정보를 제공하는 것을 라우트 한다라고 한다. 이에 관한 미들웨어이다.

    라우터 미들웨어에 관한 app 객체의 메서드이다.


    메서드 이름 설명
    app.get() GET 요청 처리
    app.post() POST 요청 처리
    app.put() PUT 요청처리
    app.del() DELETE 요청처리
    app.all() 모든방식의 요청처리


    • all() 메서드


    var items =[
        {
            name: '우유',
            price : '2000'
        },
        {
            name: '홍차',
            price : '5000'
        },
        {
            name: '커피',
            price: '5000'
        }
    ];
    
    //응답형식은 html형식, json형식, xml형식이 있다.
    
    // localhost:포트번호/data.html 로 들어오는 모든 방식의 리퀘스트를 처리한다.
    app.all('/data.html', function(request, response){
        var output = '';
        output += '<!DOCTYPE html>';
        output += '<html>';
        output += '<head>';
        output += ' <title>Data HTML</title>';
        output += '</head>';
        output += '<body>';
        items.forEach(function(item){
            output+= '<div>';
            output+= '  <h1>'+item.name+'</h1>';
            output += ' <h2>'+item.price+'</h2>'
            output +='</div>'
        });
        output +='</body>';
        output += '</html>';
        response.send(output);
    });
    
    // localhost:포트번호/data.json 로 들어오는 모든 방식의 리퀘스트를 처리한다.
    app.all('/data.json', function(request, response){
        response.send(items)
    });
    
    // localhost:포트번호/data.xml 로 들어오는 모든 방식의 리퀘스트를 처리한다.
    app.all('/data.xml', function(request, response){
        var output ='';
        output +='<?xml version ="1.0" encoding ="UTF-8" ?>';
        output +='<products>';
        items.forEach(function(item){
            output+='<product>';
            output +=' <name>'+item.name+'</name>';
            output +='  <price>'+item.price+'</price>';
            output +='</product>'
        });
        output +='</products>';
        response.type('text/xml');
        response.send(output);
    
    });