request.body always empty for multipart form data

2.7k views Asked by At

I have the following in the request being sent from the browser:

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--

This request is intercepted by a node server. Here is how it looks:

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);
});

Problem is that, I always get the req.body as empty. It works fine when the json is posted.

1

There are 1 answers

0
krampstudio On BEST ANSWER

From the body-parser documentation: https://github.com/expressjs/body-parser You need an extra middleware.

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer