body-parser node.js의 모듈로 express의 미들웨어이다. body-parser는 클라이언트에서 post 요청으로 받은 body 데이터로부터 파라미터를 편리하게 추출할 수 있다.
body-parser의 역할은 이름에서알 수 있듯이 'body'를 parsing(파싱)하는 일을 한다.
클라이언트측에서 body객체에 데이터를 담아 POSTRequest로 서버단에 전달하면 서버단에서는 express를 이용해 요청받은 req.body객체를 받아 사용한다.
그런데 body-parser가 없다면 에러가 발생하는데, 그 이유는 req.body는 body-parser를 사용하기 전에는 디폴트값으로 Undefined가 설정되기 때문이다.
예를 들어 다음과 같은 데이터를 body에 담아 POST request를 보낸다고 가정해보자
{
userID : "eunbin",
password: "password"
}
이 POST 요청을 서버에서 express를 통해 처리하려면 다음과 같은 코드를 작성해야 한다.
var express = require('express');
var app = express();
app.post('/profile', function(req, res) => {
console.log(req.body);
});
그러나 이대로 실행하면 console.log() 실행중에 오류가 발생한다.
이때 body-parser를 사용해야 하는데, 사용 방법은 다른 패키지와 같다.
npm install하고, 코드에서 require로 실행해 변수에 저장하고 , app.use로 사용하기!
npm install body-parser
↓
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser().json())
app.post('/profile', function(req, res) => {
console.log(req.body);
})
그러나 이제는 이렇게 사용하면 취소선이 생기며 코드가 제대로 실행되지 않는다.
> You don't need body-parser in Express 4.16+
What does body-parser do with express?
I don't understand why we need body-parser in an Express application, as we can get data without using body-parser. And what does it do actually and how?
stackoverflow.com
As of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.
express 버전 4.16이상부터, body-parser는 express의 기본 패키지에 포함되어있기 때문에 더이상 단독으로 다운받을 필요가 없다.
이제는 express자체에서 bodyparser의 기능을 사용할 수 있다.
// body-parser 사용
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
// express 자체 메소드 사용
app.use(express.json());
app.use(express.urlencoded());
'Programming' 카테고리의 다른 글
[번역] 팩토리함수 vs 생성자함수 vs 클래스함수 (JavaScript Factory Functions vs Constructor Functions vs Classes by Eric Elliott) (0) | 2021.06.30 |
---|---|
[Data Structure] Linked List (0) | 2021.06.16 |
[Algorithm] 프로그래머스 - level1 <체육복> (0) | 2021.06.03 |
[React] 리액트란? 리액트의 4가지 특성 (0) | 2021.06.02 |
[Algorithm] 프로그래머스 - level1 <신규아이디 추천> (0) | 2021.05.27 |