Home > other >  Express server putting out wrong value
Express server putting out wrong value

Time:10-11

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?

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");
});

CodePudding user response:

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

CodePudding user response:

const express = require("express");
const app = express();

// Make sure that all ingredients are always lowercase, this way you will avoid accidental mis-configuration.
const ingredients = ["Raisins", "Pepper", "Beef"].map((v) => v.toLowerCase());

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

  // Using `includes` is a shorter version of `arr.some((v) => v === ingredient)
  // Before checking for user-input existence, transform it to lowercase as well, so we can match no matter the casing.
  const foundIngredient = ingredients.includes(ingredient.toLowerCase());

  res.send(foundIngredient ? "In Stock!" : "Out of Stock!");
});

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