Node.js/Node.js Doc

[Node.js] bodyparser 미들웨어 사용하기

장일규 2022. 5. 8. 20:31

클라이언트단에서 사용자가 입력한 데이터를 처리하기 위해서는 두 가지 방법이 있다.

1. bodyparser 모듈(4.16이전 버전)

2. express.json

이번에는 body-parser모듈이라는 미들웨어를 사용하는 방법에 대해서 공부해보고자 합니다.

설치

$ npm install body-parser --save

cmd에 위에 명령어를 입력하면 설치할 수 있다.

 

body-parser가 없을 때 문제점: undefined

Client to Server json value

client에서 사용자가 `ilkyu`라는 이름과 `30`나이를 서버로 전달하려고 했지만, 서버에서 req.body로 요청한 값을 받아보면 undefined가 출력된다.

{
    "name": "ilkyu",
    "age": 30
}

서버에서 express를 사용하여 POST Request를 처리하는 방법은 아래와 같다.

const express = require("express");

const app = express();

app.post('/user', (req, res) =>{

 console.log(req.body) // undefined

});

body-parser 사용

서버에서 body-parser를 사용하여 POST request를 처리하는 방법은 아래와 같다.

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

app.post('/user', (req, res) => {
    res.status(StatusCodes.CREATED).json({
        message: "create"
    });
    console.log(req.body);
});

bodyParser.json()는 무엇인가?

bodyParser.json()는 application/json방식의 Content-Type데이터를 받아주는 역할을 한다.

bodyParser.urlencoded()은 무엇인가?

bodyParser.urlencoded()는 application/x-www-form-urlencoded방식의 Content-Type데이터를 받는다.

urlencoded에 extended 옵션에 값은 무엇인가?

extended에 옵션 값이 false일 경우 기본으로 내장된 querystring 모듈을 사용한다.
true일 경우 개발자가 직접 qs 모듈을 사용하여 query String을 한다.

기본값은 true이다.

querystring모듈과 qs모듈에 차이점은?

querystring

    querystring.parse("name=ilkyu&age=30) // { name: 'ilkyu', age: '30'}

qs

    qs.parse("name=ilkyu&age=30) // { name: 'ilkyu', age: '30'}

querystring과 qs 모두 기본적으로 같은 동작방식을 가지고 있지만, 전달되는 객체(object)에 depth가 있을 경우 encoding 방식에 차이점이 있다. 즉, 중첩 객체 처리이다.

Ref

What does 'extended' mean in express 4.0?