Node.js

Node.js 미들웨어 body-parser 사용법

헤이봄봄 2021. 5. 20. 11:25
middleware 

 

우리는 소프트웨어를 만들때, 다른사람이 미리 만들어놓은 소프트웨어 부품을 사용함으로서

나의 소프트웨어를 완성한다. 

 

누군가에 의해 만들어진 미들웨어를 

Third-party middleware 라고 부르며

 

그 가운데에서도 대표적으로 많이 사용되는 

body-parser 에 대해 알아보도록 하자. 

 

 

body-parser 

웹브라우저 쪽에서 요청한 정보의 본체인 body를 분석해서

우리가 필요한 형태로 가공해주는 프로그램

 

설치방법
npm install body-parser --save

 

모듈 require 시키기
const bodyParser = require('body-parser');

 

미들웨어 등록
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

 

 

위와같이 미들웨어를 등록하면,

사용자가 전송한 post데이터 request인자에

body라는 property로 접근할수있게된다.

app.post('/create_process', function (request, response) {
   console.log(request.body);
});

//{title: "CSS", description: "CSS is .. "}

이를 출력햇을때 오브젝트형태로 출력할수 있게된다. 

 

 

미들웨어를 사용하지않고 구현했던 소스와 비교해보면

훨씬 깔끔하고 가독성좋은 코드가 되는것을 확인해 볼 수 있다. 

//미들웨어 사용 전 
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: `/?id=${title}`});
          response.end();
        })
    });
});


//미들웨어 사용 후 
app.post('/create_process', function (request, response) {
    var post = request.body;
    var title = post.title;
    var description = post.description;
    fs.writeFile(`data/${title}`, description, 'utf8', function(err){
      response.writeHead(302, {Location: `/?id=${title}`});
      response.end();
    })
});