我目前正在学习如何使用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),这是我一开始完全错过的。
通过“*”改变true对我来说很有用,所以它看起来是这样的:
const cors = require('cors')({ origin: "*" })
我尝试了这种方法,因为在一般情况下,这是响应头的设置方式:
'Access-Control-Allow-Origin', '*'
请注意,这将允许任何域调用您的端点,因此它是不安全的。
此外,你可以阅读更多关于文档的内容:
https://github.com/expressjs/cors
没有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函数日志并调试任何错误
我对安德烈自己的问题有一些补充。
看起来你不需要在cors(req, res, cb)函数中调用回调,所以你可以在函数的顶部调用cors模块,而不需要在回调中嵌入你的所有代码。如果您想随后实现cors,这将更快。
exports.exampleFunction = functions.https.onRequest((request, response) => {
cors(request, response, () => {});
return response.send("Hello from Firebase!");
});
不要忘记初始化cors,就像开头提到的那样:
const cors = require('cors')({origin: true});
更新:任何需要时间的响应函数都有可能在此实现中出现CORS错误,因为它没有适当的async/await。不要在返回静态数据的快速原型端点之外使用。