【问题标题】:Fail to call firebase 'onCall' function in front end due to CORS policy由于 CORS 策略,无法在前端调用 firebase 'onCall' 函数
【发布时间】:2020-09-23 06:40:51
【问题描述】:

我正在尝试编写一个可以从 Firebase 数据库中获取数据的函数。 于是写了下面这个简单的函数,看看能不能在前端页面调用他。
但是我收到了错误消息:

访问获取 'https://us-central1-undefined.cloudfunctions.net/sayHello' 来自 来源“http://localhost:8081”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式为“no-cors”以获取禁用 CORS 的资源。

index.js”中的代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.sayHello = functions.https.onCall((data, context) => {
  const name = data.name;
  return `hello ${name} :)`.then(()=>{
    console.log('success');
  }).catch((err)=>{console.log(err)})
});

调用函数的组件中的代码:

import { db, functions, rootRef } from '../db/firebaseConfig.js';

methods: {
  sayHello(){
    const sayHello = functions.httpsCallable('sayHello');
    // call the function and pass data
    sayHello({ name: 'Peter' }).then(result => {
        console.log(result);
     });
  },

我也看过Enabling CORS in Cloud Functions for Firebase的答案。 但这对我不起作用。

【问题讨论】:

  • 您能否展示您如何实施您提到的答案(stackoverflow.com/a/42756623/3371862)中提出的解决方案?它实际上是解决方案。
  • 我添加了代码const cors = require('cors')({origin: true});,并将firebase函数更新到了最新版本。
  • 实际上,我现在意识到您使用的是可调用云函数,而不是 HTTPS 函数。见stackoverflow.com/questions/50278537/…

标签: firebase vue.js cors google-cloud-functions


【解决方案1】:

您使用函数模拟器吗? 如果是这样,您需要像这样设置它

firebase.initializeApp(config)
firebase.functions().useFunctionsEmulator("http://localhost:5001")

(将5001端口改为你使用的端口)

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 2023-02-02
    • 1970-01-01
    • 2018-12-16
    • 2021-04-10
    • 2018-11-02
    • 2021-01-23
    • 2022-12-18
    • 1970-01-01
    相关资源
    最近更新 更多