Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express server putting out wrong value

I have an array with elements and I want to compare the URL input to it.

For example when a user inputs localhost:8080/ingredients/raisins I want to return In Stock and if it’s something that’s not inside the array (eg. /ingredients/chicken), it should be Out of Stock.

However, for the time being it just returns Out of Stock, no matter the user’s input. What am I missing here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const express = require("express");
const app = express();
const ingredients = ["Raisins", "Pepper", "Beef"];

app.get("/ingredients/:ingredient", (req, res) => {
  const { ingredient } = req.params;
  const foundIngredient = ingredients.find((item) => item === ingredient);

  if (foundIngredient) {
    res.send("In Stock!");
  } else {
    res.send("Out of Stock!");
  }
});

app.listen(8080, () => {
  console.log("I am running on port 8080");
});

>Solution :

Looks like you have some error on the capitalize word , try to standardize the word before comparing. You can try to compare all with lower case .
Or as @Joel said you can use "localCompare" this to better performance comparing

const foundIngredient = ingredients.some((item) =>item.localeCompare(ingredient, "en", { sensitivity: "base" }));

if (foundIngredient) {
 res.send("In Stock!");
} else {
 res.send("Out of Stock!");
}

And also as improve not use find(), because you are looking for a boolean, not a entity,so you can use some() instead, take a look here how to use it

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading