node.jsjsonrequestinsomnia

How to parse a JSON sent via Insomnia


I have my small server with fastify, I have set all routes and now I need to test the backend to parse the JSON in the body.

...
const isJSON = (str) => {
  try {
    console.log(str);
    JSON.parse(str);
    console.log("json parsed");
  } catch(error) {
    return false;
  }

  return true;
};

const checkBody = (req, res) => {
  if(!isJSON(req.body)) {
    res.code(codes.BAD_REQUEST);
    res.header('content-type', 'text/text');
    res.send("Error: The body is not a JSON");
    throw new Error();
  }
};

...

I'm doing requests with Insomnia, writing the body like

{
  "serial": "31A15",
  "sensor_type": "Temperature",

  "value_registered": {
      "value_type": "Temperature",
      "value": "24.6",
      "unit_of_measure": "Celsius"
  },

  "value_registered_at": "02/05/2021 9:20:05"
}

But when I try to parse the JSON, the function isJSON return false.


Solution

  • I found out that fastify already parse the json in the body, and if there is an error, it send a error code. So I don't need checkBody and isJSON.