简体   繁体   中英

How to send React to Express server get Request passing id

Hello I am learning on MERN Stack dev, so I am trying to implement a get request where by I send in and ID and then try searching through the collection by the id the return the entry back to the client so I have been trying to implement this but I do not know where I am going wrong because I get a 404 response

Code below is the client side where I try to send through the get request

const ProductDetails = (props) => {
  const product_id = window.location.href.split("/")[4];
  console.log(product_id);

  const getProduct = () => {
    const url = `http://127.0.0.1:5000/single-women-clothes/id?=${product_id}`;
    Axios.get(url)
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  getProduct();
  return (
    <div>
      <h1>Details</h1>
    </div>
  );
};



router.get("/single-womens-clothes/:id", (request, response) => {
  console.log(request.params);
  MongoClient.connect(
    mongoURI,
    { useNewUrlParser: true, useUnifiedTopology: true },
    (error, client) => {
      client
        .db("OnlineStore")
        .collection("WomensClothes")
        .find(request.params.id)
        .toArray()
        .then((data) => {
          response.status(200).json(data);
        })
        .then((response) => {
          console.log("Single Female Product Fetch Successful");
        })
        .catch((error) => {
          console.log(error);
        });
    }
  );
});

Can I please get help on how I can pass the ID to the server then search through collection through this given ID

Anytime you have a 404 error, the issue is usually coming from putting the wrong url.

In your front-end:

single-women-clothes/id?=${product_id}

Backend

/single-womens-clothes/:id

You are missing an "s" in the front-end url in "womens"


To answer your second question:

You shouldn't do id?= just simply leave it as

single-women-clothes/${product_id}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM