# Node.js Express ๋ฏธ๋“ค์›จ์–ด body-parser

ํด๋ผ์ด์–ธํŠธ POST request data์˜ body๋กœ๋ถ€ํ„ฐ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ํŽธ๋ฆฌํ•˜๊ฒŒ ์ถ”์ถœํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

body-parser๋Š” ์š”์ฒญ์˜ ๋ณธ๋ฌธ์„ ํ•ด์„ํ•ด์ฃผ๋Š” node.js์˜ ๋ชจ๋“ˆ, ๋ฏธ๋“ค์›จ์–ด๋‹ค. ๋ณดํ†ต form ๋ฐ์ดํ„ฐ๋‚˜ Ajax ์š”์ฒญ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•œ๋‹ค.

# Install body-parser

npm install body-parser
yarn add body-parser
1
2

# How to Use

/* express */
const express = require('express');
const app = express();

/* body parser */
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
1
2
3
4
5
6
7

urlencoded ๋ฉ”์„œ๋“œ์˜ ({ extended: true }) ์˜ต์…˜์ด ์žˆ๋‹ค. ํ•ด๋‹น ์˜ต์…˜์ด false ๋ฉด ๊ธฐ๋ณธ์œผ๋กœ ๋‚ด์žฅ๋œ ๋…ธ๋“œ์˜ querystring ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜๊ณ , true๋ฉด ๋ณ„๋„์˜ ์„ค์น˜๊ฐ€ ํ•„์š”ํ•œ qs ๋ชจ๋“ˆ์  ์‚ฌ์šฉํ•˜์—ฌ ์ฟผ๋ฆฌ์ŠคํŠธ๋ง์„ ํ•ด์„ํ•œ๋‹ค.

# POST ์š”์ฒญ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋ฒ„์— ์ „์†กํ•˜๋Š” ๋ฒ•

POST ์š”์ฒญ์œผ๋กœ ํ•ด๋‹น ๊ฒฝ๋กœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋ฒ„์— ์ „์†กํ•  ์ˆ˜ ์žˆ๋‹ค.

app.post('/add', (req, rep) => {
  console.log(req.body);
});
1
2
3

POST ์š”์ฒญ์œผ๋กœ ์„œ๋ฒ„์— ๋ฐ์ดํ„ฐ๋ฅผ ์ „์†กํ•  ๋•Œ form ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒฝ์šฐ form HTML๋„ ์„ธํŒ…์ด ํ•„์š”ํ•˜๋‹ค. form์˜ action๊ณผ method ์†์„ฑ์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ „์†กํ•  ๋•Œ ๊ผญ ํ•„์š”ํ•œ ์†์„ฑ์ด๋‹ค.
action ์€ ์–ด๋–ค ๊ฒฝ๋กœ๋กœ ์š”์ฒญํ•  ๊ฒƒ์ธ์ง€ ์„ค์ •ํ•˜๋Š” ์†์„ฑ์ด๋ฉฐ, method ์†์„ฑ์€ GET/POST ์ค‘ ์–ด๋–ค ์š”์ฒญ์„ ํ•  ๊ฒƒ์ธ์ง€ ์„ค์ •ํ•˜๋Š” ์†์„ฑ์ด๋‹ค. ์ถ”๊ฐ€๋กœ input ์š”์†Œ์— name ์†์„ฑ์„ ๊ผญ ์ถ”๊ฐ€ํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด ์„œ๋ฒ„๋Š” ์ด ๋ฐ์ดํ„ฐ๊ฐ€ ์–ด๋–ค input์—์„œ ์ „๋‹ฌ๋œ ๋ฐ์ดํ„ฐ์ธ์ง€ ์•Œ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๊ผญ ์„ค์ •ํ•ด์ฃผ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

# HTML

<form action="/add" method="POST">
  <div class="form-group">
    <label>์˜ค๋Š˜์˜ ํ• ์ผ</label>
    <input type="text" class="form-control" name="title" />
  </div>
  <div class="form-group">
    <label>๋‚ ์งœ</label>
    <input type="text" class="form-control" name="date" />
  </div>
  <button type="submit" class="btn btn-danger">Submit</button>
</form>
1
2
3
4
5
6
7
8
9
10
11

# JS

/*
 * ํŒŒ๋ผ๋ฏธํ„ฐ ๋ณ€์ˆ˜ ๋œป
 * req: request ์š”์ฒญ
 * res: response ์‘๋‹ต
 */
app.post('/', function (req, res) {
  var post = req.body;
  console.log(post);
});
1
2
3
4
5
6
7
8
9

๊ฐ input์— ์ •๋ณด๋ฅผ ์ž…๋ ฅํ•˜๊ณ  submit ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๊ฒŒ๋˜๋ฉด ํ•ด๋‹น ๋ฐ์ดํ„ฐ๊ฐ€ ๊ฐ์ฒด๋กœ ์ „๋‹ฌ๋œ ๊ฒƒ์„ ํ„ฐ๋ฏธ๋„์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

[nodemon] restarting due to changes...
[nodemon] starting `node serve.js server.js`
listening on 8080
{ title: 'hello', date: 'hi' }
1
2
3
4

๋˜๋Š” ์ด์™€ ๊ฐ™์ด send๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ „๋‹ฌํ•ด์ฃผ๋ฉด ์„œ๋ฒ„ ํ™”๋ฉด์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

app.post('/', function (req, res) {
  res.send(req.body);
});
1
2
3
Last Updated: 2022. 6. 5. ์˜คํ›„ 3:42:39