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


当前回答

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

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

其他回答

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

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

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

希望有帮助!

这可能会有帮助。 我创建了firebase HTTP云功能与express(自定义URL)

const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const main = express();

app.post('/endpoint', (req, res) => {
    // code here
})

app.use(cors({ origin: true }));
main.use(cors({ origin: true }));
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));

module.exports.functionName = functions.https.onRequest(main);

请确保您添加了重写部分

"rewrites": [
      {
        "source": "/api/v1/**",
        "function": "functionName"
      }
]

对于它的价值,我有同样的问题,当传递应用程序到onRequest。我意识到问题在于firebase函数的请求url上的末尾斜杠。Express正在寻找'/',但我在函数[project-id].cloudfunctions.net/[function-name]上没有后面的斜杠。CORS的错误是假阴性。当我添加后面的斜杠时,我得到了我所期待的响应。

如果您不使用Express或只想使用CORS。下面的代码将帮助解决这个问题

const cors = require('cors')({ origin: true, });   
exports.yourfunction = functions.https.onRequest((request, response) => {  
   return cors(request, response, () => {  
        // *Your code*
    });
});

Go into your Google Cloud Functions. You may have not seen this platform before, but it's how you'll fix this Firebase problem. Find the Firebase function you're searching for and click on the name. If this page is blank, you may need to search for Cloud Functions and select the page from the results. Find your function, click on the name. Go to the permissions tab. Click Add (to add user). Under new principles, type 'allUsers' -- it should autocomplete before you finish typing. Under select a role, search for Cloud Functions, then choose Invoker. Save. Wait a couple minutes.

这应该能解决问题。如果没有,就这样做,并在你的函数代码中添加一个CORS解决方案,比如:

  exports.sendMail = functions.https.onRequest((request, response) => {
  response.set("Access-Control-Allow-Origin", "*");
  response.send("Hello from Firebase!");
});