express는 기본적으로 body의 값을 undefined로 처리하기 때문에, 다음과 같이 요청을 하게 되면
const express = require('express');
const app = express();
app.post('/', (req, res) => {
console.log(req.body);
});
콘솔 창에는 undefined라고 뜨게 된다.
이를 해결하기 위해선
const express = require('express');
const qs = require('qs');
const app = express();
app.post('/', (req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const post = qs.parse(body);
const title = post.title;
const body = post.body;
});
이러한 방식으로 읽을 수 있는 형태로 변환시켜주어야 한다.
이 과정을 단축시켜주는 것이 바로 Body-Parser라는 Node의 미들웨어이다. (미들웨어란, 양 측을 연결하며 중간에서 매개체 역할을 하는 것)
npm i body-parser //설치 필요
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false});
app.post('/', (req, res) => {
let title = req.body.title;
});
다음과 같이 간단하게 사용할 수 있다.
bodyParser.json 은 요청을 JSON의 형태로 파싱해주도록 하는 것이다.
또한 urlencoded의 false는 데이터의 변환 방식을 선택하는 것과 같은데,
false : querystring library // true : qs library 를 사용한다.
둘의 차이는 변환 전과 후의 차이이다.
다음과 같이 객체 안에 객체가 있는 경우,
{
title : '1번째 게시물',
body : '1번째 게시물입니다',
postinfo : {
name : 홍길동,
date : 2024-02-27
}
}
false :
{
'title' : '1번째 게시물',
'body' : '1번째 게시물입니다',
'name' : '홍길동',
'date' : '2024-02-27'
}
true :
{
title : '1번째 게시물',
body : '1번째 게시물입니다',
postinfo : {
name : '홍길동',
date : '2024-02-27'
}
}
와 같이 변환된다.
'Node.js' 카테고리의 다른 글
[Node.js] Google Vision Api OCR / 텍스트 추출하기 / Tesseract? (0) | 2024.12.11 |
---|---|
[Node.js] Multer (0) | 2024.11.20 |
[Node] passport (0) | 2024.11.08 |
[express] Session (0) | 2024.06.04 |
[Node] Axios (0) | 2024.02.28 |