expressjs/body-parser

Node.js body parsing middleware. Contribute to expressjs/body-parser development by creating an account on GitHub.

github.com

 

What are express.json() and express.urlencoded()?

I cannot find any documentation on express.json() and express.urlencoded(). What do each of them do exactly?

stackoverflow.com

 

1. Parsing 이란?

 

parsing : 가지고 있는 데이터를 내가 원하는 형태의 데이터로 ‘가공'하는 과정

parser : 파싱 과정을 하는 모듈이나 메서드를 일컫는다. 

 

내가 원하는 형식에 맞춰 해석하는 용도이므로 bodyParser 뿐만 아니라 cookieParser, JSON.parse, JSON.stringifyJSON.stringify.. 등 파서의 종류는 셀 수 없이 많다.

예를 들어 외국어를 번역할 때 어떤 언어인지 정하고 해당 언어에 맞게 구문을 해석해주는 것을 parser, 그에 따라 실제 번역하는 것을 compiler라고 할 수 있다.

 

 

 

 

2. BodyParser

HTTPpost put 요청 시 request body에 들어오는 데이터 값을 읽을 수 있는 구문으로 파싱함과 동시에
req.body 로 입력해주어 응답 과정에서 요청에 body 프로퍼티를 새로이 쓸 수 있게 해주는 미들웨어

 

클라이언트 측에서 API post와 put 메서드로 요청 시 (get delete는 불가능) body를 포함하여 보낼 수 있는데 이 값을 서버 측에서 받는다고 그대로 사용할 수 있는 것이 아니고, 서버 내에서 해석 가능한 형태로 변형해야 사용할 수 있게 되는 것이다.
이때 API 요청에서 받은 body 값을 파싱하는 역할을 수행하는 것이 bodyParser라는 미들웨어이다.

 

 

설치

npm insatll body-parser --save

 

예제

<form action="/email_post" method="post">
      email: <input type="text" name="email" /><br />
      <input type="submit" />
</form>

 

- body-parser 사용하지 않은 경우

// body-parser 없이 사용하면
app.post('/email_post', function (req, res) {
  console.log(req.body);
  res.send('post response');
});

// undefined 출력된다.

 

- body-parser 사용한 경우

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

 

post나 put으로 넘어온 데이터 중 json형식이나 encoding 된 url 데이터를 분석하도록  express 서버에 설정해주는 구문이다.

 

const express = require('express');
const app = express();
const bodyParser = require('body-parser');


// 클라이언트에서 오는 응답이 json형태 or 
// json이 아닌 그냥 post(urlencoding된) 데이터를 파싱
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.post('/email_post', function (req, res) {
  console.log(req.body);
  console.log(req.body.email);
  res.send('post response');
});

/*
출력
  { email: 'asd@asdasdasd.com' }
  'asd@asdasdasd.com'
*/

 

express 문서에 따르면 미들웨어 없이 req.body 에 접근하는 경우에는 기본으로undefined 가 설정되어 있으므로 bodyParser, multer와 같은 미들웨어를 사용하여 요청 데이터 값에 접근해야 한다고 되어있다.

클라이언트 측에서 { name: 'John', age:...}와req.body 혹은 req.body.name, req.body.job 등으로 해당 데이터에 곧바로 접근할 수 있게 된다.

반응형

'Node.js > Express' 카테고리의 다른 글

[Express] express.Router() 와 express() 차이  (0) 2020.11.05

+ Recent posts