Javascript 如何从localhost调用firebase可调用函数?
我得到这个错误: 无论何时调用此云函数:Javascript 如何从localhost调用firebase可调用函数?,javascript,firebase,vue.js,google-cloud-functions,Javascript,Firebase,Vue.js,Google Cloud Functions,我得到这个错误: 无论何时调用此云函数: const makeAdmin = firebase.functions().httpsCallable("makeAdmin"); makeAdmin({ make: "admin" }) .then(response => { console.log(response); }) .catch(err => consol
const makeAdmin = firebase.functions().httpsCallable("makeAdmin");
makeAdmin({
make: "admin"
})
.then(response => {
console.log(response);
})
.catch(err => console.error(err));
功能是:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
const auth = admin.auth();
exports.makeAdmin = functions.https.onCall(async (data, context) => {
try {
const email = context.auth.token.email || null;
const user = await auth.getUserByEmail(email);
await auth.setCustomUserClaims(user.uid, {
admin: true
});
return {
message: "admin added successfully"
};
} catch (error) {
return error;
}
});
我尝试使用cors模块,但没有成功。您需要启用
cors
,才能执行该请求:
首先安装软件包:
npm install cors
然后导入它:
const cors = require('cors')({origin: true});
我知道需要做什么,因为我已经面临同样的问题 对于本地主机::无需安装cors(最好卸载) 参考以下内容修改函数/index.js
exports.yourFuncation = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', "*")
/*Your code and response*/})
对于生产:使用相同的代码,但不使用cors中的本地主机,而是使用您的生产url
并且应该修改firefunction的firebase.json,如下所示
{
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
],
"headers": [{
"key": "Access-Control-Allow-Origin",
"value": "https://production.com/*"
}]
}}
您还需要在hosting下的firebase.json中添加cors值
"rewrites": [{
"source": "**",
"destination": "/index.html",
"headers": [{
"key": "Access-Control-Allow-Origin",
"value": "https://us-central1-projectname.cloudfunctions.net*"
}]}]}
根据需要修改内容,如果您遇到问题,请留下评论您是否也部署了该功能?是的。它是通过使用创建公共端点并从中进行测试而成功部署的,因此您可以确定这是本地主机问题。您可以在firebase web控制台中查看您的功能吗?你能检查你函数的日志吗?它是你的
index.js
文件吗?如果没有,您是否从主文件导入了此代码?是的,我尝试过<代码>常量函数=需要(“firebase函数”);const admin=require(“firebase管理员”);const cors=require(“cors”)({origin:true});admin.initializeApp();const db=admin.firestore();const auth=admin.auth();exports.makeAdmin=functions.https.onCall(异步(数据,上下文)=>{try{const uid=context.auth.uid;wait auth.setCustomUserClaims(uid,{admin:true});cors(req,res,()=>{res.send({message:“admin added successfully”});});}catch(错误){return error;})代码>那么它是否有效???