我目前正在学习如何使用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),这是我一开始完全错过的。


当前回答

对于任何试图在Typescript中这样做的人来说,这是代码:

    import * as cors from 'cors';
    const corsHandler = cors({origin: true});
        
    export const exampleFunction= functions.https.onRequest(async (request, response) => {
           corsHandler(request, response, () => { 
             //Your code here
           });
           
    });

其他回答

云功能日志有助于检查您是否卡住了。

我的问题原来是我的云函数上的一个类型错误,我有一个数字,其中一个字符串是预期的:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type number (1)

出于某种原因,这给了我cors错误的前端,它成为了几个小时的浪费。

在我的例子中,错误是由云函数调用者限制访问引起的。请将allUsers添加到云函数调用器。请抓住林克。更多信息请参考文章

如果其他解决方案都不起作用,您可以尝试在呼叫开始时添加以下地址以启用CORS -重定向:

https://cors-anywhere.herokuapp.com/

JQuery AJAX请求示例代码:

$.ajax({
   url: 'https://cors-anywhere.herokuapp.com/https://fir-agilan.web.app/gmail?mail=asd@gmail.com,
   type: 'GET'
});

我刚刚发表了一篇关于这方面的文章:

https://mhaligowski.github.io/blog/2017/03/10/cors-in-cloud-functions.html

通常,您应该使用Express CORS包,它需要一些hack才能满足GCF/Firebase Functions中的要求。

希望有帮助!

如果您更喜欢使用单个处理程序函数(参考答案)

const applyMiddleware = handler => (req, res) => {
  return cors(req, res, () => {
    return handler(req, res)
  })
}
exports.handler = functions.https.onRequest(applyMiddleware(handler))