nodejs-express-modules

Express Modules

Express 유용한 모듈

body-parser

POST 데이터 파싱

https://github.com/expressjs/body-parser

  • Express/Connect top-level generic
    1
    var express = require('express')
    2
    var bodyParser = require('body-parser')
    3
    4
    var app = express()
    5
    6
    // parse application/x-www-form-urlencoded
    7
    app.use(bodyParser.urlencoded({ extended: false }))
    8
    9
    // parse application/json
    10
    app.use(bodyParser.json())
    11
    12
    app.use(function (req, res) {
    13
      res.setHeader('Content-Type', 'text/plain')
    14
      res.write('you posted:\n')
    15
      res.end(JSON.stringify(req.body, null, 2))
    16
    })
  • Express route-specific
    1
    var express = require('express')
    2
    var bodyParser = require('body-parser')
    3
    4
    var app = express()
    5
    6
    // create application/json parser
    7
    var jsonParser = bodyParser.json()
    8
    9
    // create application/x-www-form-urlencoded parser
    10
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    11
    12
    // POST /login gets urlencoded bodies
    13
    app.post('/login', urlencodedParser, function (req, res) {
    14
      res.send('welcome, ' + req.body.username)
    15
    })
    16
    17
    // POST /api/users gets JSON bodies
    18
    app.post('/api/users', jsonParser, function (req, res) {
    19
      // create user in req.body
    20
    })
  • Change accepted type for parsers
    1
    var express = require('express')
    2
    var bodyParser = require('body-parser')
    3
    4
    var app = express()
    5
    6
    // parse various different custom JSON types as JSON
    7
    app.use(bodyParser.json({ type: 'application/*+json' }))
    8
    9
    // parse some custom thing into a Buffer
    10
    app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
    11
    12
    // parse an HTML body into a string
    13
    app.use(bodyParser.text({ type: 'text/html' }))
Share