javascript - 调用 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 端点时,我得到了错误:
错误:无法处理请求
解决方案
推荐阅读
- flutter - 启动 tel: 和电子邮件时出现颤振问题
- react-native - Drawer.Navigator 在里面添加图片,React Native
- algorithm - 最短剩余时间作业优先调度算法说明
- python-3.x - Python中的频谱图
- pandas - 子 DataFrame 保持与原始数据帧的链接
- kotlin - Kotlin 调用就地合约有哪些好处?
- javascript - 如何使用 Map 检查嵌套对象数组中是否存在键
- javascript - 在 for 循环中将数组作为函数的参数传递
- r - 组内的ggplot scale_fill_manual
- mysql - SQL查询使用count时返回0