Frankie
Frankie

Reputation: 51

Check POST body request syntax and format with Node.js Express

I would like to simply check the syntax of POST request body that my server gets on the route called '/route' :

/// My code ///

app.use(express.json());

function isJsonString(str) {
    try {
        console.log('JSON Parsing function...');
        JSON.parse(str);
    } 
    catch (e) {
        console.log("Error : " + e);
        return false;
    }
    return true;
}

app.post('/route', function(req, res) {

    var isJsonString_result = isJsonString(req.body);
    console.log(isJsonString_result);

    if(isJsonString_result === true){
        console.log('OK continue');
        res.status(200).send('ok');
    }
    else{
        console.log('Wrong body format');
        res.status(404).send('ko');
    }
})

/// The results ///

Here are the results I get when I send a POST request from Postman with this JSON (sent with header "Content-Type": "application/json") :

{
  "key1": "value1",
  "key2": "value2"
}

/// Postman result ///

ko

/// Console.log ///

JSON Parsing function...

Error : SyntaxError: Unexpected token o in JSON at position 1 false

Wrong body format

=> the explanation seems to be that "JSON.parse" can not parse existing JSON...

So first question : how can I check if the body is correct JSON format please ?

and with this other JSON with missing quotes (always sent with header "Content-Type": "application/json") :

{
  "key1": "value1",
  "key2: "value2"
}

/// Postman result ///

Long "Error" message begining with "SyntaxError: Unexpected token v in JSON at position 32"

/// Console.log ///

The same :

SyntaxError: Unexpected token v in JSON at position 32 at JSON.parse ()

... ...

=> No idea how to handle this issue, if there are many POST requests with wrong body syntax, my "log" can potentially grow very fast.

Can you help me please with both questions ?

Thank you !

Upvotes: 5

Views: 6709

Answers (2)

Kyaw Kyaw Soe
Kyaw Kyaw Soe

Reputation: 3370

You got error because you try to parse json object to json object, JSON.parse() is use for parsing json string to json object

e.g. JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

in your case you don't need to check it is json string or not, since you use app.use(express.json()); it will check the in-coming body is correct json format or not, if not it will ignore it.

so basically you will only get safe json object from your req.body

Upvotes: 0

robertklep
robertklep

Reputation: 203359

The issue is that you're using express.json() before the routes that are trying to validate the JSON data:

app.use(express.json());

That will try and parse the incoming JSON data, and return an error when it isn't valid. This is the reason why your second request fails.

The reason why your first request, with valid JSON, fails is that req.body will contain the result of JSON.parse(); that's what express.json() does. So it will be an object, not a string, which is why your check fails (because JSON.parse can only be used on strings or buffers).

There's an option verify for express.json() that you can use to validate the incoming data:

app.use(express.json({
  verify : (req, res, buf, encoding) => {
    try {
      JSON.parse(buf);
    } catch(e) {
      res.status(404).send('ko');
      throw Error('invalid JSON');
    }
  }
}));

Upvotes: 5

Related Questions