简体   繁体   中英

node.js body-parser bad interpretation of Content-Type:x-www-form-urlencoded and Form-data JSON

I have a client request with

Content-type: Content-Type:application/x-www-form-urlencoded; charset=UTF-8

And Form-Data like this (json):

{"jsonrpc":"2.0","method":"print","params":{"id":"lp0","doc":"<section>
<p>&nbsp;sitedemo&nbsp;&nbsp;&nbsp;&nbsp;</p><br><barcode>                   CLODGCGMM                    
</barcode><br><br><hr><drawer></drawer><br></section>"},"id":1501151330950}

The node.js server use body-parser middleware like this :

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

A console.log(request.body) give me something like this:

{ '{"jsonrpc":"2.0","method":"print","params":{"id":"lp0","doc":"<section>
<p>': '',
'nbsp;': '',
'nbsp;sitedemo': '',
'nbsp;':'',
'&nbsp;</p><br><barcode>':''
'.......}'}

A json object is built having keys made by lines and values null .

How can i retrieve the exact object send by client (i have no access to client)

Thank you.

The client is broken when it's stating in the headers that the request body is URL-encoded but it's sending JSON.

If that's really the situation, you need to prevent those requests from being decoded by body-parser , and do the decoding manually.

Instead of this:

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

Try this:

app.use(
  bodyParser.raw({ type : 'application/x-www-form-urlencoded' }),
  function(req, res, next) {
    try {
      req.body = JSON.parse(req.body)
    } catch(e) {
      req.body = require('qs').parse(req.body.toString());
    }
    next();
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM