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


当前回答

没有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函数日志并调试任何错误

其他回答

Firebase团队提供了两个示例函数来演示CORS的使用:

具有日期格式的时间服务器 要求认证的HTTPS端点

第二个示例使用与当前使用的cors不同的工作方式。

考虑像这样导入,如示例所示:

const cors = require('cors')({origin: true});

函数的一般形式是这样的

exports.fn = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        // your function body here - use the provided req and res from cors
    })
});

通过“*”改变true对我来说很有用,所以它看起来是这样的:

const cors = require('cors')({ origin: "*" })

我尝试了这种方法,因为在一般情况下,这是响应头的设置方式:

'Access-Control-Allow-Origin', '*'

请注意,这将允许任何域调用您的端点,因此它是不安全的。

此外,你可以阅读更多关于文档的内容: https://github.com/expressjs/cors

补充我的经验。 我花了几个小时试图找到为什么我有CORS错误。

碰巧我重命名了我的云功能(这是我在一次大升级后尝试的第一次)。

因此,当我的firebase应用程序使用错误的名称调用云函数时,它应该抛出404错误,而不是CORS错误。

修复我的firebase应用程序中的云函数名称修复了这个问题。

我在这里填了一份关于这个的错误报告 https://firebase.google.com/support/troubleshooter/report/bugs

这可能会有帮助。 我创建了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"
      }
]

更新答案:使用cors库与Typescript支持:

安装科尔斯

npm i -S cors
npm i --save-dev @types/cors

index.ts:

import * as cors from "cors";
const corsHandler = cors({ origin: true });

// allow cors in http function
export const myFunction = functions.https.onRequest((req, res) => {
corsHandler(req, res, async () => {

// your method body

 });
});

旧的回答: (不再工作) 找到了一种不导入任何“cors”库的方法来启用cors。它还可以使用Typescript,并在chrome版本81.0中进行了测试。

exports.createOrder = functions.https.onRequest((req, res) => {
// browsers like chrome need these headers to be present in response if the api is called from other than its base domain
  res.set("Access-Control-Allow-Origin", "*"); // you can also whitelist a specific domain like "http://127.0.0.1:4000"
  res.set("Access-Control-Allow-Headers", "Content-Type");

  // your code starts here

  //send response
  res.status(200).send();
});