在Firebase中启用云功能中的CORS [英] Enabling CORS in Cloud Functions for Firebase
问题描述
我目前正在学习如何使用Firebase的新云端功能,而我遇到的问题是我无法存取通过AJAX请求写入的功能。我得到没有访问控制允许起源错误。这里是我写的函数的一个例子:
$ p $ 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'); $(b)
exports.test = functions.https.onRequest((request,response)=> {
cors(request,response,()=> {
response.status (500).send({test:'Testing functions'});
})
})
我做错了什么?
更新:
Doug Stevenson 的回答有帮助。添加({origin:true})解决了这个问题,我还必须将 response.status(500)
更改为 response.status(200)
我完全错过了。
有两个示例功能,由Firebase团队提供,演示如何使用CORS:
第二个示例使用与您目前使用的cors不同的工作方式。
此外,请考虑像这样导入,如示例所示:
const cors = require('cors')({o rigin:true});
I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:
exports.test = functions.https.onRequest((request, response) => {
response.status(500).send({test: 'Testing functions'});
})
The function sits in this url: https://us-central1-fba-shipper-140ae.cloudfunctions.net/test
Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events
This is how I did it:
var cors = require('cors');
exports.test = functions.https.onRequest((request, response) => {
cors(request, response, () => {
response.status(500).send({test: 'Testing functions'});
})
})
What am I doing wrong? I would appreciate any help with this.
UPDATE:
Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500)
to response.status(200)
which I completely missed at first.
There are two sample functions provided by the Firebase team that demonstrate the use of CORS:
The second sample uses a different way of working with cors than you're currently using.
Also, consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});
这篇关于在Firebase中启用云功能中的CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!