Avery246813579 Avery246813579 - 11 months ago 76
JSON Question

How do you reject an invalid JSON body using Express or Body-Parser

I'm creating an application that only accepts a body type of json and uses body-parsers and express. The problem that keeps showing up is if I send an invalid json body, then my program will throw a stupid error back to the user, and in the console. How would I prevent this console error and reject a request with an improper JSON body.

Thanks in advance,
Avery.

PS. Here is some example code to show what I'm doing:

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

app.use(bodyParser.json());

app.post('/test', function(req, res){
res.status(200).send("Hi");
});

app.listen(8081, function(){
console.log("Server is running");
});

Answer Source

You need to attach some error handling middleware to your app. How you handle that error is up to you, but as an example of how you'd do it:

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

app.use(bodyParser.json());

// this is a trivial implementation
app.use((err, req, res, next) => {
  // you can error out to stderr still, or not; your choice
  console.error(err); 

  // body-parser will set this to 400 if the json is in error
  if(err.status === 400)
    return res.status(err.status).send('Dude, you messed up the JSON');

  return next(err); // if it's not a 400, let the default error handling do it. 
});

app.post('/test', function(req, res){
   res.status(200).send("Hi");
});

app.listen(8081, function(){
   console.log("Server is running");
});