首页 > 解决方案 > 调用 Firebase Cloud Functions 时出现 CORS 错误

问题描述

我有以下 hello world Firebase 云功能:

const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("Hello from Firebase!");
});

然后我从网页调用它,如下所示:

<script>
    // Initialize Firebase
    var config = { <config information copy-pasted from firebase console>
    };
    firebase.initializeApp(config);

    let helloWorld = firebase.functions().httpsCallable('helloWorld');
    console.log(helloWorld)
    helloWorld().then(function (result) {

    })
</script>

但是,我收到以下错误:

CORS 策略已阻止从源“null”获取(我的云函数 url)的访问权限:对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头资源。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

我仍然可以直接访问 HTTP 端点。我究竟做错了什么?

我在查看后尝试了以下操作:在 Cloud Functions for Firebase 中启用 CORS

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

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {

    return cors(req, res, () => {
        res.status(200).send('Hello World!')
    })
    //response.set('Access-Control-Allow-Origin', '*');
    //response.send("Hello from Firebase!");
});

但是,当我访问 HTTP 端点时,我得到了错误:

错误:无法处理请求

标签: javascriptfirebasehttpgoogle-cloud-functions

解决方案


推荐阅读