javascript - 使用请求参数从 Cloud Function 内部运行查询
问题描述
我在使用请求参数从 Cloud Functions 运行查询以构建查询表单 HTTP 调用时遇到问题。过去,我从云函数中运行查询很好,没有错误。当我尝试使用从请求中获得的参数运行查询时,出现了我的问题。
当我在函数中硬编码文档的位置时,它工作正常,但是当我尝试构建查询时,它返回状态代码 200。我还记录了构建的查询,它正在注销正确的内容,但没有数据正在被退回。它仅在文档路径被硬编码时返回数据。请参阅下面的代码。
Query looks like this
https://us-central1-<project-id>.cloudfunctions.net/getData/CollectionName/DocumentName
export const getData = functions.https.onRequest((request, response) => {
const params = request.url.split("/");
console.log("the params 0 "+params[0]);
console.log("the params 1 "+params[1]);
console.log("the params 2 "+params[2]);
//Build up the document path
const theQuery = "\'"+params[1]+"\/"+params[2]+"\'";
console.log("the query "+theQuery); <-- logs out right result in the form 'Collection/Document'
//Fetch the document
const promise = admin.firestore().doc("\'"+params[1]+"\/"+params[2]+"\'").get() <---- This doesnt work, building the query
//const promise = admin.firestore().doc('collectionName/DocID').get() <---- This hard coded and it works
promise.then(snapshot => {
const data = snapshot.data()
response.send(data)
}).catch(error => {
console.log(error)
response.status(500).send(error);
})
});
我尝试使用不同的方法并为数据字段命名,如下所示
Query looks like this
https://us-central1-<project-id>.cloudfunctions.net/getData?CollectionName=CName&DocumentID=Dname
export const getData = functions.https.onRequest((request, response) => {
const collectName = request.query.CollectionName;
const DocId = request.query.DocumentName;
//Build up the document path
const theQuery = "'"+collectName+"\/"+collectName+"'";
console.log("the query "+theQuery); <---Logs out correct result
//Fetch the document
const promise = admin.firestore().doc(theQuery).get() <-- Building the query does not work
//const promise = admin.firestore().doc('collectionName/DocID').get() <---- This hard coded and it works
promise.then(snapshot => {
const data = snapshot.data()
response.send(data)
}).catch(error => {
console.log(error)
response.status(500).send(error);
})
});
在这两种情况下,当从 URL 构建请求时,它不会返回任何数据,也不会返回任何错误。而且我确信我试图获取的文档存在于数据库中。我错过了什么吗?
解决方案
试试request.path
。然后你可以获取路径组件,例如request.path.split("/")[1]
使用Express时的语法request.query
是有效的。这在一些文档中被引用,但没有明确表示需要 Express。这很令人困惑。
要正确处理动态输入,您可能会更幸运地使用 Express 并创建路由和处理程序。这个Firebase 页面有一些使用它的项目的链接。
在 Firebase 上使用 Express 进行演练设置。
推荐阅读
- javascript - 角材料选择列表复选框不可见检查
- css - Angular - 如何实现类似于工具提示的 UI 界面,但这会让我在其中放置一些控件并与它们交互
- css - 这段代码可以减少并且仍然具有相同的效果吗?
- c# - 如何通过单击按钮使表单标题动态更改?
- google-analytics - 谷歌分析活动/来源/媒体未显示
- python - 为什么对 zip() 调用的列表理解会返回一个包含 zip 对象的列表,而不是 zip() 的返回值列表?
- c - 如何将 STDIN 传递给程序并将其输出存储到变量中?C
- jenkins - Jenkins 中的自动部署构建失败
- python - Python - 拖放到终端作为输入?macOS -zsh
- html - 执行两个 url 之一的 webview