【问题标题】:Node GET by ID API通过 ID API 获取节点
【发布时间】:2021-10-11 21:48:26
【问题描述】:

我已按照说明创建 NODE API here。 我正在尝试使用 NODE 应用程序为我的 React UI 提供数据的一些端点。 数据库是 mongodb,我有一个“商店”集合。

我有 2 个 GET 调用:

  1. 一个检索所有商店
  2. 按 ID 检索商店

节点 app.js:

app.get('/viewstores', (request, response) => {
  storesCollection.find({}).toArray((error, result) => {
    if (error) {
      return response.status(500).send(error);
    }
    response.send(result);
  });
});

app.get("/viewstores/:id", (request, response) => {
  storesCollection.findOne({ "_id": new ObjectId(request.params.id) }, (error, result) => {
      if(error) {
          return response.status(500).send(error);
      }
      
      response.send(result);
  });
});

我在 React 中从 axios 进行 API 调用。 如果我调用第一个 API 来检索所有商店,完全没有问题,但如果我尝试按 ID 进行 API 调用,我仍然会从第一个 API 获取所有商店。 看来我无法通过 ID api 定位 GET。

反应应用

React.useEffect(() => {
    axios.get('http://localhost:5000/viewstores', {
       params: { _id: params.storesid}
    })
    .then(({data}) => {
      console.log("DATA ==> ", data)
    })
    .catch(error => console.log("ERROR API GET ==> ", error))
  }, [])

MongoDB 存储示例:

_id: ObjectId("12345")
businessname:"ABC"
businessaddress:"address abc 1"

知道为什么当我尝试按 ID 调用 GET 时,我总是取回整个集合吗?

提前致谢。 乔。

【问题讨论】:

    标签: node.js reactjs mongodb api axios


    【解决方案1】:

    假设params.storesid12345, 你当前的 React 代码向http://localhost:5000/viewstores?_id=12345 发送请求,并到达路由/viewstores。要到达/viewstores/:id 路由,URL 应该类似于http://localhost:5000/viewstores/12345,然后 Express 会将 URL 中的12345 部分捕获到request.params.id。你可以试试下面的代码:

    React.useEffect(() => {
        axios.get(`http://localhost:5000/viewstores/${params.storesid}`)
        .then(({data}) => {
          console.log("DATA ==> ", data)
        })
        .catch(error => console.log("ERROR API GET ==> ", error))
      }, [])
    

    您可以在official document 中阅读有关 Express 路由参数的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 2013-11-16
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2012-07-13
      • 2014-10-30
      相关资源
      最近更新 更多