当我的客户端调用https://us-central1-myapp.cloudfunctions.net/getWebsiteIdByName/mywebsite,我希望调用以下firebase函数,并返回一个具有匹配名称的文档。我已经写了下面的函数,但一直得到错误:Error: could not handle the request
。我该怎么解决这个问题?我的代码如下:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.getWebsiteIdByName = functions.https.onRequest((req: any, res: any) => {
let websiteName = req.url.split("/");
websiteName = websiteName[websiteName.length - 1];
res.set('Access-Control-Allow-Origin', '*');
const website = admin.firestore().collection('websites', (ref: any) => ref.where('name', '==', websiteName).limit(1)).get();
return website.then(function (response: any) {
if (response[0].data()) {
res.end(`{ "websiteId": "${response[0].data()['id']}" }`);
} else {
res.end(`{ "websiteId": null }`);
}
console.log('Request successful!');
}).catch((error: any) => console.log('Request failed: ', error));
});
尝试2
exports.getWebsiteIdByName = functions.https.onRequest((req: any, res: any) => {
let websiteName = req.url.split("/");
websiteName = websiteName[websiteName.length - 1];
res.set('Access-Control-Allow-Origin', '*');
const website = admin.firestore().collection('websites', (ref: any) => ref.where('name', '==', websiteName).limit(1)).get();
return website.then(function (response: any) {
if(response.empty) {
res.end(`{ "websiteName": null }`);
} else {
res.end(`{ "websiteName": ${JSON.stringify(response.docs[0].get())}`);
}
console.log('Request successful!');
}).catch((error: any) => console.log('Request failed: ', error));
});
最终发现,我返回了一个QuerySnapshot,所以必须以不同的方式处理它。
exports.getWebsiteIdByName = functions.https.onRequest((req: any, res: any) => {
let websiteName = req.url.split("/");
websiteName = websiteName[websiteName.length - 1];
res.set('Access-Control-Allow-Origin', '*');
const website = admin.firestore().collection('websites', (ref: any) => ref.where('name', '==', websiteName).limit(1)).get();
return website.then(function (response: any) {
if (response.empty) {
res.end(`{ "websiteId": null }`);
} else {
res.end(`{ "websiteId": ${JSON.stringify(response.docs[0].data()['id'])} }`);
}
console.log('Request successful!');
}).catch((error: any) => console.log('Request failed: ', error));
});