Study/Node.js

Node.js 미들웨어 사용하기(bodyParser, compression)

토기발 2022. 9. 7. 17:10

 

오늘도 생활코딩 강의를 들으며 정리한 내용이다.

노드에서 미들웨어를 사용하여 코드를 더욱 간결하게 만드는 방법을 공부했다.

 

 

bodyParser

app.post('/create_process', function(request, response){
  var body = '';
  request.on('data', function(data){
      body = body + data;
  });
  request.on('end', function(){
      var post = qs.parse(body);
      var title = post.title;
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8', function(err){
        response.writeHead(302, {Location: `/?page/${title}`});
        response.end();
      })
  });

 

기존에 있던 파일을 생성하는 코드이다.

qs는 쿼리스트링인데 이전 포스팅에서 이건 권장하지 않는다는 얘기를 했었다. 그래서 그런지 보기 싫게 취소선이 그어져 있어서 거슬렸는데 미들웨어인 bodyParser를 사용하여 없애줄 수 있었다.

 

먼저 bodyParser를 설치한다.(는 express 최신버전에는 이미 설치되어있다는 말이 있다..)

 

npm install body-parser --save

터미널에 이렇게 써주면 설치가 된다.

 

그리고

var bodyParser = require('body-parser');

모듈로 선언하고 가져온다.

app.use(bodyParser.urlencoded({extended: false}));

이것도 추가한다.

 

그러면 bodyParser를 사용할 준비는 끝난다.

아까 위에 쓴 코드를 bodyParser를 이용하여 고쳐보자.

 

  var post = request.body;
  var title = post.title;
  var description = post.description;
  fs.writeFile(`data/${title}`, description, 'utf8', function(err){
    response.writeHead(302, {Location: `/?page/${title}`});
    response.end();
  })

 

이렇게 간략화 할 수 있다.

변경된 부분은 맨 위에 var post = request.body; 가 된 것 뿐이고 타이틀부터는 기존코드 그대로이다.

그리고 body를 설명하는 윗부분은 모두 지워주면 된다.

 

추가로 response로 시작하는 2줄도 express의 기능을 이용하여 아래처럼 간략화할 수 있다.

response.redirect(`/page/${title}`);

 

 

compression 

 

 

해당 문서는 24.3KB다.

만약 10MB씩 여러사람에게 전송된다고 하면 어떻게 될까?  돈과 시간 등등 부담이 클 것이다.

이것을 방지하고자 데이터를 압축할 수 있는 미들웨어가 탄생했다.

압축하기- 풀기를 compression이 대신 해준다.

 

npm install compression --save

먼저 compression 설치를 한다.

 

var compression = require('compression')

이번에도 모듈선언하고 가져오기.

 

app.use(compression({ filter: shouldCompress }))

마찬가지로 추가한다.

 

 

 

캐시삭제를 하고 크롬에서 우클릭-검사-네트워크에서 확인해보면

2.4KB로 줄어든 것을 볼 수 있다! 

또 응답 헤더를 보면

gzip 방식으로 압축되어 전송된 것을 확인할 수 있다.