我目前正在学习如何使用Firebase的新云函数,我遇到的问题是我无法访问我通过AJAX请求编写的函数。我得到了“No 'Access-Control-Allow-Origin'”错误。下面是我写的函数示例:
exports.test = functions.https.onRequest((request, response) => {
response.status(500).send({test: 'Testing functions'});
})
函数位于这个url中:
https://us-central1-fba-shipper-140ae.cloudfunctions.net/test
Firebase文档建议在函数中添加CORS中间件,我尝试过,但对我不起作用:https://firebase.google.com/docs/functions/http-events
我是这样做的:
var cors = require('cors');
exports.test = functions.https.onRequest((request, response) => {
cors(request, response, () => {
response.status(500).send({test: 'Testing functions'});
})
})
我做错了什么?如果你能帮我,我会很感激。
更新:
道格·史蒂文森的回答很有帮助。添加({origin: true})修复了这个问题,我还必须将response.status(500)更改为response.status(200),这是我一开始完全错过的。
没有CORS解决方案对我有效…直到现在!
Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...
dr -如果没有CORS解决方案工作,检查您的firebase函数日志并调试任何错误
Firebase v2的云功能
Firebase v2的云函数现在允许您直接在HTTP选项中配置cors。它的工作不需要任何第三方软件包:
import { https } from 'firebase-functions/v2';
export myfunction = https.onRequest({ cors: true }, async (req, res) => {
// this will be invoked for any request, regardless of its origin
});
请注意:
在撰写本文时,v2正在公开预览中。
目前v2中只支持区域的一个子集。
函数名被限制为小写字母、数字和破折号。
你可以在一个代码库中同时使用v1和v2函数。为了提高可读性,请更新导入以分别访问firebase-functions/v1或firebase-functions/v2。