Body-parser gets empty body when content type has multiple values

I am upgrading from express 3 to 4, the syntax parsing middleware has changed so I use body-parser

and it looks good in most situations:

var bodyParser = require('body-parser');

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

      

But I have a third party service that will call one of my specific urls to notify messages, it works fine in express 3 but doesn't work in expression 4 because it is req.body

empty

I am debugging the request header, found that Content-Type

- application/x-www-form-urlencoded; text/html; charset=UTF-8

and notapplication/x-www-form-urlencoded

so I tested it in the curl, when I delete text/html; charset=UTF-8

, req.body

can accurately show my body of the message.

so what should I do then? this is a third party service, they have no reason to change their code, is there a node way? TCS

+3


source to share


2 answers


according to the doc http://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.14.17 the request header is Content-Type

incorrect. so the problem is that the request header has two types of media and the body-parser binder handles it text/html

.

Finally I wrote a middleware especially for this query, found if the words are there application/x-www-form-urlencoded

, then I qs.parse(buffString)

solve it temporarily



app.use(function(req, res, next){
  if(/^\/pay\/ali\/notify/.test(req.originalUrl)){
    req.body = req.body || {};
    if ('POST' != req.method) return next();
    var contenttype = req.headers['content-type'];
    if(!/application\/x-www-form-urlencoded/.test(contenttype)) return next();
    req._body = true;
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){ buf += chunk });
    req.on('end', function(){
      req.body = qs.parse(buf);
      next();
    });
  }else{
    next();
  }
});

      

+2


source


Or you can just force urlencoded

for Alipay like app.post('/alipay', bodyParser.urlencoded({ extended: true, type: function() {return true;} }))



0


source







All Articles