Firebase调用云函数时没有使用’no-cors’选项。

huangapple go评论75阅读模式
英文:

Firebase make call to cloud function without 'no-cors' option

问题

我无法从浏览器调用云函数,因为存在 CORS 问题。文档中没有提到如何禁用它的选项。这是否可能?如果不行,为什么它是 Firebase Web 应用的基本示例之一?

错误信息:

CORS 策略阻止了从来源 'https://projectepic-adcf9.web.app' 尝试访问 'https://us-central1-projectepic-adcf9.cloudfunctions.net/helloWorld'。

服务器端代码:

const { onRequest } = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
const cors = require("cors")({ origin: true });

exports.helloWorld = onRequest((request, response) => {
    cors(req, res, () => {
        logger.info("Hello logs!", { structuredData: true });
        res.set("Access-Control-Allow-Origin", "*");
        res.send("Hello from Firebase!");
    });
});

请注意,这段代码中的 cors(req, res, ...) 应更正为 cors(request, response, ...)

英文:

I am unable to make calls to cloud functions from the browser because of Cors. There is nowhere in the documentation that talks about options for disabling it. Is it even possible? If not, why is it one of the basic examples of firebase web apps?

code:

                firebase
				.functions()
				.httpsCallable("helloWorld")()
				.then(() => {});

The code on server side shouldn't matter since it's a client-side issue of disabling the CORS policy. Is it even possible?

The error:

Access to fetch at 'https://us-central1-projectepic-adcf9.cloudfunctions.net/helloWorld' from origin 'https://projectepic-adcf9.web.app' has been blocked by CORS policy

There are similar questions out there but they all provide solutions that don't work.

Server side code:

const { onRequest } = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
const cors = require("cors")({ origin: true });

// Create and deploy your first functions
// https://firebase.google.com/docs/functions/get-started

exports.helloWorld = onRequest((request, response) => {
	cors(req, res, () => {
		logger.info("Hello logs!", { structuredData: true });
		res.set("Access-Control-Allow-Origin", "*");
		res.send("Hello from Firebase!");
	});
});

答案1

得分: 2

你混淆了可调用类型的函数和普通的HTTP函数。它们不同,并且不能一起使用。

你的客户端代码试图调用一个可调用函数,但它是以普通的HTTP函数形式部署的,使用onRequest。如果你想编写并调用一个可调用函数,你应该查看文档中的示例,并使用onCall而不是onRequest

英文:

You are mixing up callable type functions and normal HTTP functions. They are not the same, and they do not work together.

Your client code is trying to invoke a callable function, but it's deployed as a normal HTTP function using onRequest. If you want to write and invoke a callable function, you should review the example in the documentation on that and use onCall instead of onRequest.

huangapple
  • 本文由 发表于 2023年7月3日 03:29:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定