简体   繁体   English

如何将 React 发送到 Express 服务器获取请求传递 ID

[英]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你好,我正在学习 MERN Stack dev,所以我正在尝试实现一个 get 请求,通过我发送和 ID,然后尝试通过 id 搜索集合,将条目返回给客户端,所以我一直在尝试实现这个,但我不知道我哪里出错了,因为我收到了 404 响应

Code below is the client side where I try to send through the get request下面的代码是我尝试通过 get 请求发送的客户端

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我能否获得有关如何将 ID 传递给服务器然后通过此给定 ID 搜索集合的帮助

Anytime you have a 404 error, the issue is usually coming from putting the wrong url.每当您遇到 404 错误时,问题通常是由于放置了错误的 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"您在“女性”的前端网址中缺少“s”


To answer your second question:回答你的第二个问题:

You shouldn't do id?= just simply leave it as你不应该做id?=只是简单地将其保留为

single-women-clothes/${product_id}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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