Javascript jsfetch:有没有一种方法可以通过Fetch请求传递表名?
我有两个表,一个用于用户,一个用于todo,当单击todo按钮时,我使用以下代码获取所有todo。我想使用相同的函数来获取所有用户 index.html:Javascript jsfetch:有没有一种方法可以通过Fetch请求传递表名?,javascript,mongodb,fetch,Javascript,Mongodb,Fetch,我有两个表,一个用于用户,一个用于todo,当单击todo按钮时,我使用以下代码获取所有todo。我想使用相同的函数来获取所有用户 index.html: displayItems() { fetch('/getItems',{ method: "get", }).then(response => { return response.json(); }).then((data)=>{ this
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时是否有方法传递表名?您可以向
displayItems
函数发送一个参数,并将其作为get paramater
发送
displayItems(tableName) {
fetch('/getItems?table='+tableName,{
method: "get",
}).then(response => {
return response.json();
}).then((data)=>{
this.items = data
});
}
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);
}
});
});
然后您可以在服务器端使用req.query
like访问它
displayItems(tableName) {
fetch('/getItems?table='+tableName,{
method: "get",
}).then(response => {
return response.json();
}).then((data)=>{
this.items = data
});
}
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);
}
});
});
它只是参数中的字符串传递,并将其与存储对象中的值进行映射,但是,如果您想在请求中传递集合名称,请注意不要在端点/URL中公开集合名称。如果您使用mongoose,则可以尝试以下操作:但不要在请求中传递完全相同的集合名称,这可能不是问题,但请想一想,为什么要在URL中公开所有集合名称:-)。一般来说,最好在服务器端编写单独的RESTful API端点来查询不同的表/集合,而不要公开实际的集合名称。一个URL gettodos代表todo,另一个URL可能getUsers代表Users。@JonathanSchiffner,如果要使用模板文本,请使用backticks(转义键下面的键)。正常的单一报价不起作用。。