我有一个网络应用程序已经使用 Firebase 和 Firestore 进行身份验证。我想从网络应用程序调用我的函数,所以我使用
onCall
,因为函数文档推荐它。
当我在本地主机上运行我的网络应用程序时,我收到此错误:
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.
服务器:
import { onCall, HttpsError } from "firebase-functions/v2/https";
import { onDocumentWritten } from "firebase-functions/v2/firestore";
import * as logger from "firebase-functions/logger";
exports.plusone = onCall({
cors: true,
}, (request) => {
const email = request.auth?.token.email;
const num = request.data.num;
logger.log(email + " tried to increase his number by one:" + num);
return {
finalNum: num + 1,
}
})
客户:
const functions = getFunctions();
const plusone = httpsCallable(
functions, 'plusone'
)
plusone().then((result) => {
console.log(result.data.message)
})
CORS 是一项通过浏览器强制执行的安全功能,已经有相当长一段时间了,只有服务器(在您的情况下是云功能)允许的来源才允许从该客户端(浏览器)发出请求,这就是为什么您会在第一名。
您已经启用了cors,您应该允许您的源向您的云功能发出请求
const { onRequest } = require("firebase-functions/v2/https");
exports.plusone = onRequest(
{ cors: true },
(req, res) => {
res.set('Access-Control-Allow-Origin', '*'); // do this for development purpose, when you are in production change that to your origin where you are hosting your webpage
res.status(200).send("Hello world!");
}
);