【问题标题】:JS Fetch: Is there a way to pass on a table name with a fetch reequest?JS Fetch:有没有办法通过获取请求传递表名?
【发布时间】:2020-05-20 12:18:37
【问题描述】:

我有两张表,一张用于用户,一张用于待办事项,当单击待办事项按钮时,我使用以下代码获取所有待办事项。我想使用相同的功能来获取所有用户。

index.html:

    displayItems() {
      fetch('/getItems',{
        method: "get",
      }).then(response => {
        return response.json();
      }).then((data)=>{
        this.items = data
      });
    }

app.js:

app.get('/getItems', (req,res)=>{      
  db.getDB().collection(tableName).find({}).toArray((err,documents)=>{
    if(err)
      console.log(err);
    else {
      console.log(documents);
      res.json(documents);
    }
  });
});

只要我在 app.js 中设置 tableName 就可以正常工作,但是我必须编写单独的函数来从两个不同的表中获取项目。

当我在 index.html 中调用 fetch 时,是否有办法传递表名,具体取决于单击了哪个按钮?

【问题讨论】:

  • 这只是一个传入参数的字符串并将其映射到存储对象中的值,但如果您想在请求中传递它,请注意不要在端点/url中公开集合名称。
  • 如果你使用猫鼬,那么你可以试试这个:stackoverflow.com/questions/51702041/… 但不要在请求中传入完全相同的集合名称,这可能不是问题,但想想你为什么要公开所有你的网址中的集合名称:-)。
  • 一般来说,最好在服务器端编写单独的 RESTful API 端点来查询不同的表/集合,以免暴露实际的集合名称。一个 URL gettodos 用于 todo,另一个 URL 可能是 getUsers 用于用户。

标签: javascript mongodb fetch


【解决方案1】:

您将参数发送到您的displayItems 函数并将其作为get paramater 发送,例如

displayItems(tableName) {
  fetch('/getItems?table='+tableName,{
    method: "get",
  }).then(response => {
    return response.json();
  }).then((data)=>{
    this.items = data
  });
}

然后你可以在你的服务器端使用req.query 来访问它

app.get('/getItems', (req,res)=>{      
  db.getDB().collection(req.query.table).find({}).toArray((err,documents)=>{
    if(err)
      console.log(err);
    else {
      console.log(documents);
      res.json(documents);
    }
  });
});

【讨论】:

  • @JonathanSchiffner ,如果您想使用模板文字,请使用反引号(转义键下方的键)。正常的单引号不起作用..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2019-05-20
  • 2021-12-10
  • 2021-06-17
  • 2022-10-25
相关资源
最近更新 更多