Why is my code returning "success" instead of the actual ruling?

Issue

I am building a project that checks if ingredients meet a certain requirement (halal or haram). I have used MongoDB to store the info about ingredients, and express to handle the requests.

When I send a get request to ingredients/{ingredientname} I’m supposed to get the ruling back. That’s what it did when I tested it with Postman but for some reason, when I use the website to do it, I get "success" back.

Here’s my express code

app.route("/ingredients/:name").get((req, res) => {
  Ingredient.findOne({ name: req.params.name }, (err, foundIngredients) => {
    if (foundIngredients) {
      res.send(foundIngredients.ruling);
    } else {
      res.send("No match");
    }
  });
});

Here’s my jQuery code

$("#check-btn").click(() => {


  // I store the ingredients in an array
  ingredientsToCheck.forEach((e) => {
    $.get(`/ingredients/${e}`, (req, res) => {
      console.log(res);
    });
  });

});

I hope this is enough. If needed, I’ll post my entire code.

Solution

Looking at the code you posted you assume that jQuery get expects a callback with req and res. Looking at https://api.jquery.com/jquery.get/ it would seem that it just expects a callback with data.

Try to change your code to:

$("#check-btn").click(() => {


  // I store the ingredients in an array
  ingredientsToCheck.forEach((e) => {
    $.get(`/ingredients/${e}`, (data) => {
      console.log(data);
    });
  });

});

Helpful tip is to add debugger before the console.log to understand what kind of data your server is gonna return.

Answered By – ssbarbee

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published