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

问题描述

使用Firebase HTTP函数时,CORS仍然存在问题.

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

这是我的Web控制台错误:

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:

Using 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:17