1. body-parser
HTTP 요청의 본문(body)을 쉽게 파싱하도록 도와주는 미들웨어
req.body는 body-parser를 사용하기 전에는 디폴트 값으로 Undefined이 설정되서 그냥 사용 시 에러 발생
요청 데이터를 서버에서 처리하기 쉽도록 데이터 포맷 지원
- JSON (application/json)
- URL-encoded (application/x-www-form-urlencoded)
- Raw (application/octet-stream)
- Text (text/plain)
2. 사용 방법
npm install body-parser
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// JSON 데이터를 파싱하는 미들웨어 설정
app.use(bodyParser.json());
// URL-encoded 데이터를 파싱하는 미들웨어 설정
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000, () => {
console.log('Server is running on port 3000.');
});
3. 예제
JSON 형식의 이름(name)과 이메일(email)을 포함하는 POST 요청을 보내면,
서버에서 데이터를 파싱하여 저장 작업을 수행한 후 응답
{
name : "할리갈리",
email : "https://halligalli0.tistory.com/"
}
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 미들웨어 설정: JSON 및 URL-encoded 데이터를 파싱
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// R사용자의 정보를 저장하고 응답을 보내는 POST 엔드포인트
app.post('/user', (req, res) => {
const { name, email } = req.body;
console.log(`User name: ${name}, Email: ${email}`);
res.status(200).json({ message: `User ${name} with email ${email} saved successfully!` });
});
app.listen(3000, () => {
console.log('Server is running on port 3000.');
});
반응형
'개발정리 (nodeJS)' 카테고리의 다른 글
[nodeJS] Node.js와 Express에서 미들웨어 (Middleware) 사용하기 (0) | 2023.06.20 |
---|---|
[nodeJS] 변수 선언하기 (var, let, const) (0) | 2023.06.19 |
[nodeJS] Axios로 HTTP 요청하기 (0) | 2023.06.16 |
[nodeJS] Multer로 파일 업로드 구현하기 (0) | 2023.06.15 |
[nodeJS] Moment로 날짜, 시간 포맷 바꾸기 (0) | 2023.06.14 |