我无法使用请求参数来通过HTTP调用构建查询来从Cloud Functions运行查询。过去,我从云函数运行查询很好,没有错误。当我尝试使用从请求中获取的参数运行查询时,就会出现我的问题。
当我在函数中对文档的位置进行硬编码时,它可以正常工作,但是当我尝试构建查询时,它返回状态码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构建请求时,该请求均不返回任何数据,也不返回任何错误。而且我确定我要提取的文档存在于数据库中。我想念什么吗?
答案 0 :(得分:0)
尝试request.path
。然后,您可以获取路径分量,例如request.path.split("/")[1]
使用{strong> Express 时request.query
的语法有效。一些文档中引用了此方法,但并未明确要求Express。令人困惑。
要正确处理动态输入,使用Express以及创建路由和处理程序可能会有更多运气。 Firebase page包含使用它的某些项目的链接。
Walkthough set-up在Firebase上使用Express。