Firebase HTTP 函数 CORS [英] Firebase HTTP function CORS

查看:18
本文介绍了Firebase HTTP 函数 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Firebase HTTP 函数时仍然遇到 CORS 问题.

I'm still having problems with CORS when using Firebase HTTP functions.

这是我的网络控制台错误:

Here is my web console error:

Response to preflight request doesn't pass access control check: No 
'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. The 
response had HTTP status code 404.

这是我的功能:

const cors = require('cors')({ origin: true });
const express = require('express');
const functions = require('firebase-functions');

const app = express();
const validate_user = require('./validate_user_id_token.js');
const charge_card = async(req, res) => {
  // ...
}

app.use(cors);
app.use(validate_user);
app.use(charge_card);

exports.foo = functions.https.onRequest(app);

我想我已经阅读了每一个 Firebse CORS 问题.我还提供了样本的近似副本 这里.

I think I've read over every single Firebse CORS question. I also have a near replica of the sample provided here.

请帮忙:)

我调用的 URL 是正确的(使用 texdiff.com 只是为了确定,函数日志显示它已执行但返回 404).由于未知原因,无论如何都会返回 404.也许这就是 CORS 机制?

The URL I am calling is correct (used texdiff.com just to be sure, and functions logs are showing it as executed but returning 404). For reasons unknown, a 404 is returned regardless. Perhaps that is CORS mechanism?

更新:通过在我的 onRequest 处理程序中使用 cors(),我得到了不使用 express 的工作:

Update: I got things working without using express by putting using cors() in my onRequest handler:

exports = module.exports = functions.https.onRequest(async(req, res) => {
    cors(req, res, () => {});
    await charge_card(req, res);
});

不理想,但现在可以使用:/

Not ideal, but it works for now :/

推荐答案

根据 Firebase 文档,有几个对 CORS 配置的引用:

According to the Firebase documentation, there are a couple of references to CORS configuration:

使用 CORS:

您可以启用 CORS 的使用,方法是在该功能,就像您在更新问题时所做的那样:

You can enable the use of CORS by calling it within the function, just like you did in your update to the question:

// Usage of the `cors` express middleware
return cors(req, res, () => {
  // TO-DO
});

此外,如果您已有 Express 应用,您可以启用 CORS 通过这样做:

Also if you have an already existing Express app, you can then enable CORS by doing:

const app = express();
app.use(cors({ origin: true }));

这是您在第一步中已经完成的,但是 { origin: true } 定义存在差异,所以可能是相关的.

This is what you had already done on the first step, but there's the difference in the { origin: true } definition, so maybe that is related.

无论如何,根据文档,在请求中添加 cors 确实没问题.

In any case, as per the documentation it looks like it is indeed fine to add the cors within the request.

这篇关于Firebase HTTP 函数 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆