Home > Mobile >  Express Js: If Else Statement only returns boolean
Express Js: If Else Statement only returns boolean

Time:07-25

I am stumped!

I am learning Express.js, all is going smoothly, but for some reason when I try and use an if else statement, the code block does not execute... I only get TRUE or FALSE. The condition is working just fine, but the code block for IF or Else just will not fire.

I am checking to see if a product exists within my JSON file based on the ID. If the product exists, it should return the product, if not I want to set a status error with a message... any insights would be appreciated.

I am using the app.get route to run the following

 const found = res.json(products.inventory.some(item => item.id === parseInt(req.params.id)));

if(found){
     res.json(products.inventory.filter(item => item.id === parseInt(req.params.id)));
}else{
    res.status(400).json({msg: "The requested Product cant be found!"});
}

Running http://localhost:5000/api/products/3 in Insomnia or the Browser results in the following:

Its just True or False... no content

Insomnia Response

Thank you for your time...

CodePudding user response:

Because you use res.json in this line:

const found = res.json(products.inventory.some(item => item.id === parseInt(req.params.id)));

The response has been sent to the client already. So you only receive the boolean value and the block after that doesn't execute.

You don't need res.json to check if the product exists.

const found = products.inventory.some(item => item.id === parseInt(req.params.id));
  • Related