Why does bodyparser.json parse multipart / formdata?

I am trying to parse multipart / from-data with multer middleware. This is my request:

POST /api/files HTTP/1.1
Host: localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: f55caef0-1d59-fe80-f6ae-00e38fcbc92a

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="guia1"; filename="guia_1_MC_2012_2c.pdf"
Content-Type: application/pdf

----WebKitFormBoundary7MA4YWxkTrZu0gW

This is my app.js code:

var express    = require('express');        
var app        = express();                    
var bodyParser = require('body-parser');
var validator = require('express-validator'); 
var multer = require('multer');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer({ dest: './files/'}));
app.use(validator());

When I do this, I get the following error (now updated):

Error: invalid json 
at parse (.../node_modules/body-parser/lib/types/json.js:72:15) 
at .../node_modules/body-parser/lib/read.js:98:18 
at IncomingMessage.onEnd (.../node_modules/body-parser/node_modules/raw-body/index.js:136:7) 
at IncomingMessage.g (events.js:180:16) 
at IncomingMessage.EventEmitter.emit (events.js:92:17) 
at _stream_readable.js:920:16 
at process._tickCallback (node.js:415:13)

So it seems that bodyParser.json () parses data when it should not.

+4
source share
1 answer

Just found out that body-parser is working fine !! The fact is that the postman set the content type for the / json application when sending multipart / form-data by default, and also hid the header. Thanks loganfsmyth !!

+11
source

All Articles