对于多部分表单数据,request.body总是为空

时间:2015-06-24 11:22:00

标签: angularjs node.js express body-parser

我在浏览器发送的请求中有以下内容:

Remote Address:127.0.0.1:80
Request URL:http://doctor.com/api/v2/chat/message
Request Method:POST
Status Code:501 Not Implemented
**Response Headers**
view source
Access-Control-Allow-Headers:Content-Type,X-Requested-With
Access-Control-Allow-Methods:POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:61
Content-Type:text/html; charset=utf-8
Date:Wed, 24 Jun 2015 11:16:33 GMT
ETag:W/"3d-70662653"
X-Powered-By:Express
**Request Headers**
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:39235
Content-Type:multipart/form-data; boundary=----WebKitFormBoundary3qsbh041bbj3MYfd
Cookie:serviceToken=558a86bb69f3197ab93fd64c
DNT:1
Host:doctor.com
Origin:http://doctor.com
Pragma:no-cache
Referer:http://doctor.com/platform/chat
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
Request Payload
------WebKitFormBoundary3qsbh041bbj3MYfd
Content-Disposition: form-data; name="id"

55896d9bc57f69df66284176
------WebKitFormBoundary3qsbh041bbj3MYfd
Content-Disposition: form-data; name="attachment"; filename="Screen Shot 2015-06-24 at 3.18.10 am.png"
Content-Type: image/png


------WebKitFormBoundary3qsbh041bbj3MYfd--

此请求被节点服务器拦截。以下是它的外观:

var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var fs = require('fs');
var path = require('path');
var request = require('request');
var _ = require('underscore-node');
var express = require('express');

app.use(bodyParser.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended:false}));

app.use('/api/*', function (req, res, next) {
    console.log(req.body);
});

问题在于,我总是将req.body视为空。发布json时它可以正常工作。

1 个答案:

答案 0 :(得分:2)

来自正文解析器文档:https://github.com/expressjs/body-parser 你需要一个额外的中间件。

  

由于它们复杂而且不能处理多部分主体   通常是大自然。对于多部分机构,您可能感兴趣   以下模块:

     
      
  • busboy and connect-busboy
  •   
  • multiparty和connect-multiparty
  •   
  • 强大
  •   
  • multer
  •