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 !
How to handle the POST request body in Node.js without using a framework 1 Capturing the POSTed data. Each field in the form is delimited by the ampersand (&) character and the key and values are... 2 Parsing the data. 3 Limitations. You would have noticed that uploading a file sends only the file name to the backend and not the file... More ...
In order to handle POST requests in Express JS, there are certain changes that we will need to make. These are: We will need to download and install body-parser. This is a middle-ware layer which will help us handle POST requests in Node.js using Express framework.
In order to see the Node.js Express REST API GET method in action, do the following: Open up the node.js command prompt from your start menu. Type node and then the path where your node.js server is, followed by the server file name. In our case, it will be: c:\wamp\www ode\server.js
In Node.JS you can handle client’s data using GET and POST methods. However, in order to do that, you first have to install the express module. This is also called as building Node.js REST API with Express.
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');
}
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With