I would like to simply check the syntax of POST request body that my server gets on the route called '/route' :
- check if the body's format is actually JSON,
- check if the body's syntax is correct (no missing brackets or missing quotes).
/// 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 !