Express服务器输出错误的值

neekobn8  于 2022-10-12  发布在  Node.js
关注(0)|答案(2)|浏览(158)

我有一个带有元素的数组,我想将URL输入与它进行比较。

例如,当用户输入localhost:8080/ingredients/raisins时,我想返回In Stock,如果它不在数组中(例如。/ingredients/chicken),则应为Out of Stock

但是,目前它只返回Out of Stock,而不考虑用户的输入。我错过了什么吗?

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

g0czyy6m1#

看起来你在大写单词上有一些错误,试着在比较之前将该单词标准化。你可以试着把它们都用小写字母来比较。或者正如@Joel所说,您可以使用“localCompare”来进行更好的性能比较

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

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

另外,由于改进了不使用find(),因为您要查找的是布尔值,而不是实体,所以您可以使用some(),看看here如何使用它

huwehgph

huwehgph2#

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

相关问题