【发布时间】: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