为什么bodyparser.json正在解析multipart / formdata?

时间:2014-12-03 22:30:55

标签: node.js parsing express multipartform-data

我正在尝试使用multer中间件解析multipart / from-data。这是我的帖子请求:

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

这是我的app.js代码:

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

当我这样做时,我收到以下错误(现已更新):

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)

所以似乎bodyParser.json()正在解析数据,而不应该解析数据。

1 个答案:

答案 0 :(得分:12)

刚刚发现身体解析器工作正常!!事情就是邮递员在提交multipart / form-data时将内容类型设置为application / json,默认情况下也隐藏了Header。谢谢loganfsmyth !!