问题描述
我目前正在学习如何为 Firebase 使用新的 Cloud Functions,我遇到的问题是我无法访问通过 AJAX 请求编写的函数.我收到无 'Access-Control-Allow-Origin'"错误.这是我写的函数的一个例子:
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'});
})
该函数位于此网址中:https://us-central1-fba-shipper-140ae.cloudfunctions.net/test
Firebase 文档建议在函数中添加 CORS 中间件,我已经尝试过,但它对我不起作用:https://firebase.google.com/docs/functions/http-events
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
我就是这样做的:
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.
更新:
Doug Stevenson 的回答很有帮助.添加 ({origin: true}) 解决了这个问题,我还必须将 response.status(500)
更改为 response.status(200)
我一开始完全错过了.
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.
推荐答案
有两个示例函数 由 Firebase 团队提供,用于演示 CORS 的使用:
There are two sample functions provided by the Firebase team that demonstrate the use of CORS:
第二个示例使用与您当前使用的不同的 cors 工作方式.
The second sample uses a different way of working with cors than you're currently using.
考虑像这样导入,如示例所示:
Consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});
你的函数的一般形式是这样的:
And the general form of your function will be like this:
exports.fn = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// your function body here - use the provided req and res from cors
})
});
这篇关于在 Cloud Functions for Firebase 中启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!