【发布时间】:2021-01-18 14:35:36
【问题描述】:
我正在努力从在 react/ionic 上运行的网络应用程序移动应用程序调用 firebase 函数。
情况是我有一个汽车日记应用程序,对于特定车辆,我有加油/维修等的子集合。当用户想要移除车辆时,我也想要移除它的子集合,但我们都知道没有内置函数。据我了解,实现这一目标的正确方法是创建一个 firebase 函数。问题来了……这是我与他们的第一次碰撞,现在我要为此比赛 3 天。
这是函数/index.js:
import * as functions from 'firebase-functions';
export const cleanupAfterVehicle = functions.runWith({ timeoutSeconds: 540 }).https.onRequest(async
(request, response) => {
const firebase_tools = require('firebase-tools');
const userId = request.body.userId;
const vehicleId = request.body.vehicleId;
const collectionPath = `users/${userId}/vehicles/${vehicleId}/repairs`;
const token = 'MY TOKEN';
await firebase_tools.delete(collectionPath, {
project: 'project',
recursive: true,
yes: true,
token: token,
});
});
package.json
{
"name": "functions",
"scripts": {
"build": "tsc",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1",
"firebase-tools": "^7.16.2"
},
"devDependencies": {
"typescript": "^3.8.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
在我试图调用它的应用程序服务中:
private async cleanupAfterVehicleRemove(vehicleId: string): Promise<void> {
let cleanupAfterVehicleFunction = functions.httpsCallable('cleanupAfterVehicle');
await cleanupAfterVehicleFunction({ userId: window.authContext.userId, vehicleId: vehicleId
}).then((result) => console.log(result));
}
firebase 日志中的第一个问题:
TypeError: firebase_tools.delete is not a function
at exports.cleanupAfterVehicle.functions.runWith.https.onRequest (/workspace/lib/index.js:13:32)
at cloudFunction (/workspace/node_modules/firebase-functions/lib/providers/https.js:51:16)
at process.nextTick (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:99:17)
at process._tickCallback (internal/process/next_tick.js:61:11)
示例中的所有地方都显示为从 firebase_tools 调用 delete 方法,但在没有导入它的任何地方。也许这是问题之一,但我无法解决它。尝试了很多次,几乎阅读了与我的问题类似的任何内容。
第二个问题是我在调用函数时无法解决CORS问题。
Access to fetch at 'https://us-central1-myProjectId.cloudfunctions.net/cleanupAfterVehicle' from
origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the
requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
根据firebase CLI,函数在firebase中部署成功。如果您需要有关该问题的更多信息,请说出来。
如果有人帮助我进入这些功能,我将非常高兴。
最好的问候!
【问题讨论】:
-
请编辑问题以将其缩小到一个问题。有多个问题的帖子可能会因为离题而关闭。我建议在不同的帖子中单独处理 CORS。
标签: reactjs firebase google-cloud-functions