我目前正在学习如何使用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),这是我一开始完全错过的。
在devtool控制台中,同样的访问允许控制源错误,我找到了其他具有更现代语法的解决方案:
我的CORS问题是存储(不是RTDB也不是浏览器…),然后我没有信用卡(正如上述解决方案所要求的那样),我的无信用卡解决方案是:
安装gsutil:
https://cloud.google.com/storage/docs/gsutil_install#linux-and-macos
创建cors。Json文件通过终端加载与gsutil
gsutil cors set cors.json gs://[ your-bucket ]/-1.appspot.com
https://firebase.google.com/docs/storage/web/download-files#cors_configuration
没有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团队提供了两个示例函数来演示CORS的使用:
具有日期格式的时间服务器
要求认证的HTTPS端点
第二个示例使用与当前使用的cors不同的工作方式。
考虑像这样导入,如示例所示:
const cors = require('cors')({origin: true});
函数的一般形式是这样的
exports.fn = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// your function body here - use the provided req and res from cors
})
});