본문 바로가기
개발정리 (nodeJS)

[nodeJS] body-parser로 JSON 파싱하기

by 할리갈리0 2023. 6. 17.

1. body-parser

HTTP 요청의 본문(body)을 쉽게 파싱하도록 도와주는 미들웨어

req.body는 body-parser를 사용하기 전에는 디폴트 값으로 Undefined이 설정되서 그냥 사용 시 에러 발생

 

요청 데이터를 서버에서 처리하기 쉽도록 데이터 포맷 지원

  1. JSON (application/json)
  2. URL-encoded (application/x-www-form-urlencoded)
  3. Raw (application/octet-stream)
  4. 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.');
});

 

반응형