返回列表

express 接收 x-www-form-urlencoded, application/json, text/plain, multipart/form-data

默认分类 2020/04/17 08:50

代码如下:

'use strict'

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

var app = express()
var port = 8000

app.all('*', function(req, res, next) {
    console.log('req.url: ' + req.url)
    next()
})
app.all('/?', function(req, res) { res.send('Hi') })
app.all('/hi', function(req, res) { res.send('Hi world') })


// POST /api/users gets JSON bodies
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/api/www', urlencodedParser, function (req, res) {
  // create user in req.body
  res.send({
    body: req.body
  })
  // 浏览器下测试代码:
  // var xhr = new XMLHttpRequest();
  // xhr.open('POST', '/api/www', false); // 第三个参数表明是同步的 xhr
  // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
  // // xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
  // xhr.send('a=123&b=456');
})

// POST /api/users gets JSON bodies
// create application/json parser
var jsonParser = bodyParser.json()
app.post('/api/json', jsonParser, function (req, res) {
  // create user in req.body
  res.send({
    body: req.body
  })
  // 浏览器下测试代码:
  // var xhr = new XMLHttpRequest();
  // xhr.open('POST', '/api/json', false); // 第三个参数表明是同步的 xhr
  // xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  // // xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
  // xhr.send(JSON.stringify({a: 678}));
})

// POST /api/users gets JSON bodies
// create text/plain parser
var textParser = bodyParser.text({ type: 'text/plain' })
app.post('/api/text', textParser, function (req, res) {
  // create user in req.body
  res.send({
    body: req.body
  })
  // 浏览器下测试代码如下:
  // var blob3 = new Blob([JSON.stringify({a:123})], { type: 'text/plain; charset=UTF-8' })
  // navigator.sendBeacon('/api/text', blob3)
  // 或者: 
  // navigator.sendBeacon('/api/text', 'aa=123&bb=qwe')
})

// multipart/form-data
app.post('/api/form', function(req, res) {
  var form = new Formidable.IncomingForm()
  form.uploadDir = './public/tmp'
  form.keepExtensions = true

  form.parse(req, function(err, fields, files) {
    console.log(fields)
    console.log(files)

    res.send({
      fields: fields,
      files: files.length
    })
  })
  // 浏览器下测试代码:
  // var form = new FormData();form.append('aaa', 456);navigator.sendBeacon('http://cm.bilibili.com/api/form', form)
})

var server = app.listen(port, function() {
    console.log('Example app listening at http://0.0.0.0:%s', port)
});


>> 留言评论