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


当前回答

在https上使用cors。onRequest与Typescript像这样:

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

export const pingFunctionWithCorsAllowed = functions.https.onRequest((request, response) => {
  corsHandler(request, response, () => {
    response.send(`Ping from Firebase (with CORS handling)! ${new Date().toISOString()}`);
  });
});

从源

其他回答

请参阅下面我如何设置我的快车与CORS。

“https://pericope。app'是我的Firebase项目的自定义域。

看起来所有其他答案都推荐起源:true或*。

我很犹豫是否允许所有的起源,因为它将允许任何人访问api。如果您正在创建一个公共服务,这是没问题的,但如果您正在使用您的数据做任何事情,这都是有风险的,因为它是一个特权环境。例如,这个管理SDK绕过您为Firestore或Storage设置的任何安全规则。

//Express
const express = require('express');
const app = express();

const cors = require('cors');
app.use(cors({
  origin: 'https://pericope.app'
}));

我对安德烈自己的问题有一些补充。

看起来你不需要在cors(req, res, cb)函数中调用回调,所以你可以在函数的顶部调用cors模块,而不需要在回调中嵌入你的所有代码。如果您想随后实现cors,这将更快。

exports.exampleFunction = functions.https.onRequest((request, response) => {
    cors(request, response, () => {});
    return response.send("Hello from Firebase!");
});

不要忘记初始化cors,就像开头提到的那样:

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

更新:任何需要时间的响应函数都有可能在此实现中出现CORS错误,因为它没有适当的async/await。不要在返回静态数据的快速原型端点之外使用。

通过这么多的搜索,我可以在相同的firebase文档中找到这个解决方案,只是在路径中实现cors:

import * as express from "express";
import * as cors from "cors";


const api = express();
api.use(cors({ origin: true }));
api.get("/url", function);

链接firebase文档:https://firebase.google.com/docs/functions/http-events

更新答案:使用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();
});

一个额外的信息,只是为了那些在一段时间后谷歌这个:

如果你正在使用firebase托管,你也可以设置重写,例如一个url (firebase_hosting_host)/api/myfunction重定向到(firebase_cloudfunctions_host)/doStuff函数。这样,由于重定向是透明的并且是服务器端的,所以您不必处理cors。

你可以在firebase.json中设置一个重写部分:

"rewrites": [
        { "source": "/api/myFunction", "function": "doStuff" }
]