开发者

Catching Illegal JSON POST Data in Express?

开发者 https://www.devze.com 2023-04-05 20:00 出处:网络
When creating a POST request with valid JSON, the bodyParser parses the body of the POST request correctly. However, if I submit an invalid JSON string as the body, I receive the error:

When creating a POST request with valid JSON, the bodyParser parses the body of the POST request correctly. However, if I submit an invalid JSON string as the body, I receive the error:

SyntaxError: Unexpected token ILLEGAL
at parse (native)
at IncomingMessage.<anonymous>(/home/.../middleware/bodyParser.js:69:15)
...

So, it appears that the body parser is failing during the parsing of th开发者_开发知识库e body. However, I would like to catch this failure and return an error. I'm unsure what I can do to catch it, so any help would be appreciated. Thanks.


This is in the connect.js bodyParser middleware. It DOES do a try/catch and then calls next(err). You should be able to catch this error and handle with additional custom code using the app.error() callback hook. http://expressjs.com/guide.html#error-handling


For some reason, when using express/connect, JSON.parse doesn't throw exceptions, which is why your error handler doesn't fire.

I've logged an issue with express to find out what's going on, but in the meantime you can use this workaround:

express.bodyParser.parse['application/json'] = function(data) {
  var result = JSON.parse(data)
  if (typeof result != 'object') {
    throw new Error('Problems parsing JSON')
  }
  return result;
}
app.use(express.bodyParser());

update: this issue is not familiar to the author of express, so I am wondering if it's another library causing it. Will have to dismantle my code piece by piece to figure out where this behaviour is being introduced.


Try to put your

app.use(express.bodyParser()); after app.use(express.errorHandler(...))

solved it for me.

You may also adapt the following code to manage the error

express.bodyParser.parse['application/json'] = function(req, options, fn){
  var buf = '';
  req.setEncoding('utf8');
  req.on('data', function(chunk){ buf += chunk });
  req.on('end', function(){
  try {
    req.body = buf.length
      ? JSON.parse(buf)
      : {};
    fn();
  } catch (err){
    fn(new Error('Problems parsing JSON'));
  }
 });
};


bodyParser must be above app.use(app.router), it doesn't matter relative location to error handler as Perki

0

精彩评论

暂无评论...
验证码 换一张
取 消