首页 > 解决方案 > Firebase 函数“httpsCallable”本地主机测试 CORS 错误

问题描述

服务器代码

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.hello = functions.https.onCall((data, context) => {
  console.log(data.text);
  return 123;
});

客户代码

const myFunc = firebase.functions().httpsCallable('hello');
myFunc({text: 'world'}).then((rslt)=>{
  console.log('rslt:', rslt);
});

但这是行不通的。我在客户端浏览器控制台收到错误消息。

CORS 策略已阻止从源“ http://localhost:5000 ”获取“https:// ==skip== /hello”的访问权限:对预检请求的响应未通过访问控制检查:重定向未通过允许预检请求。

我怎么解决这个问题?我在谷歌指南文档中没有找到解决方案。

我看到评论并添加内容。

查询未到达服务器。

如果我在功能部署后尝试它工作正常。

但它不会显示在本地控制台上,而是显示在 firebase 控制台上。

如何进行本地服务器调用?

每次测试功能时都进行部署是很疯狂的。

标签: firebasecorsgoogle-cloud-functions

解决方案


很难从给定的代码中看出为什么您的请求违反了Cross-Origin Resource Sharing。阅读有关此问题的内容并找出导致它的 HTTP 请求中包含的内容(无论是否有意)。可能是标题?

同时,您可以通过以下方式在 Firebase 函数中启用 CORS require("cors")

const cors = require("cors")({origin: true});
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.hello = functions.https.onCall((data, context) => {
  cors(data, context, () => {
     console.log(data.text);
     res.send("123");
  }
});

关于 Firebase Functions 的本地测试,您可以使用以下命令:

firebase serve --only functions


Firebase 托管/功能的本地测试

在 Firebase 函数中启用 CORS


推荐阅读