bodyParser
본문 데이터 parsing을 도와주는 node package
npm - body-parser
기존 방식
...
} else if (req.method === 'POST') {
if (req.url === '/user') {
let body = '';
// 요청의 body를 stream 형식으로 받음
req.on('data', data => {
body += data;
});
// 요청의 body를 다 받은 후 실행됨
return req.on('end', () => {
console.log('POST 본문(Body):', body);
const { name } = JSON.parse(body); // name은 클라이언트에서 폼 전송할때 보낸 객체다.
const id = Date.now();
users[id] = name;
res.writeHead(201, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
}
body-parser
본문에 있는 데이터를 해석하여 req.body객체로 만들어주는 미들웨어이다.
form 데이터 또는 AJAX 요청의 데이터를 처리.
멀티파트(이미지, 동영상, 파일) 데이터는 처리하지 못한다.(multer 모듈 사용)
사용예시
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.json()); // 클라이언트에서 application/json 데이터를 보냈을때 파싱해서 body 객체에 넣어줌
app.use(express.urlencoded({ extended: true })); // 클라이언트에서 application/x-www-form-urlencoded 데이터를 보냈을때 파싱해서 body 객체에 넣어줌
app.get('/', (req, res) => {
req.body.name // 위의 바디파서 미들웨어 덕분에 사용할 수 있다.
res.send('Hello, index');
});
express.json()
:application/json
타입의 데이터를 body 객체로 parsing 해준다.express.urlencoded()
:application/x-www-form-urlencoded
타입의 데이터를 body 객체로 변환해준다extended
가 true이면 querystring 모듈을 사용하여 쿼리스트링을 해석하고extended
가 false이면 qs 모듈을 사용하여 쿼리스트링을 해석하고
express 4.16.0 버전 부터 json과 form 데이터를 parsing하는 것은 내장되었지만, 그 외 형식은 body-parser 설치하여 사용할 수 있다.