본문 바로가기
  • 기록
Node.js

[Node.js] body-parser

by juserh 2022. 4. 5.

1. body-parser: body 데이터를 분석(parse)하여 req.body로 출력해주는 것

https://www.npmjs.com/package/body-parser

 

body-parser

Node.js body parsing middleware. Latest version: 1.20.0, last published: 2 days ago. Start using body-parser in your project by running `npm i body-parser`. There are 20723 other projects in the npm registry using body-parser.

www.npmjs.com

$ npm install body-parser

 

예시코드

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})