【问题标题】:Firebase Functions "httpsCallable" localhost test CORS error [duplicate]Firebase 函数“httpsCallable”本地主机测试 CORS 错误 [重复]
【发布时间】:2020-02-29 07:22:46
【问题描述】:

服务器代码

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);
});

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

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

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

我看到 cmets 并添加内容。

查询未到达服务器。

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

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

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

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

【问题讨论】:

  • 查询是否到达了服务器端的 console.log?

标签: firebase cors google-cloud-functions


【解决方案1】:

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

与此同时,您可以使用 require("cors") 在 Firebase Functions 中启用 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


Local testing of Firebase Hosting / Functions

Enabling CORS in Firebase Functions.

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 2020-07-13
    • 2018-10-16
    • 1970-01-01
    • 2018-08-13
    • 2020-09-10
    • 2018-04-21
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多