【问题标题】:Firebase CORS issueFirebase CORS 问题
【发布时间】:2019-03-10 20:19:41
【问题描述】:

我构建了一个 react 应用程序,并将其部署在 firebase 上。每当用户搜索时,我都会收到此错误。

Failed to load https://food2fork.com/api/search?key=0882376145a8bcae6c3cee&q=fish&count=50: Redirect from
    'https://food2fork.com/api/search?key=0882376145a8107c5946c3cee&q=fish&count=50' to
    'https://www.food2fork.com/api/search
    key=0882376145a8bcae390107c5946c3cee&q=fish&count=50'
    has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. Origin 'https://recipe-finder-26e0e.firebaseapp.com' is therefore not allowed access.

由于我是新手,我无法弄清楚如何在 firebase 中启用 CORS,我认为这是问题所在。如果有人能告诉我如何启用 CORS,我将不胜感激。

编辑:源代码链接 --> https://github.com/AdiBev/Recipe-Finder

更新:一开始我不明白 CORS 需要由后端处理。感谢@Ben。 Ayoub 向我解释。

如果它对像我这样遇到同样问题的其他人有所帮助,我发现了一篇很棒的文章,并且在那里提到了一些代理。 链接--->https://gist.github.com/jesperorb/6ca596217c8dfba237744966c2b5ab1e

【问题讨论】:

  • 请添加您一直在使用的源代码。不要使用已部署应用程序的链接。 URL 可能会改变,然后这个问题在将来就没有用了。
  • 感谢您让我知道该链接。我现在已经添加了源代码。
  • 请在问题中添加相关的源代码。不是作为 repo 的链接。

标签: reactjs firebase cors firebase-hosting


【解决方案1】:

除了Ben. Ayoub 的解决方案之外,如果只是您的应用程序尝试与函数通信并且它不是更广泛的外部 API 的一部分,那么您可能值得研究 HTTPS Callable 函数。

它们的工作方式类似于 HTTPS 端点,但摆脱了 CORS 的麻烦。

import * as functions from 'firebase-functions';

export const listener = functions.https.onCall((data, context) => {
  if (data) {
    throw new functions.https.HttpsError('invalid-argument');
  }

  return {
    some: 'json',
  };
}

您不需要像在 HTTP 端点云函数中那样使用 requestresponse 参数。

它接受 JSON,因为它是 context,并返回一个简单的 JSON 对象。

编辑

为了回答您的原始问题,云功能可以使用 CORS

import * as functions from 'firebase-functions';

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

export const listener = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    return;
  });

  // cloud function logic

  res.json({ some: 'json' });
});

【讨论】:

  • 嗨,您能告诉我在哪里添加此代码吗?在 firebase 函数 index.js 文件中?我对此一无所知。如果您能详细告诉我如何执行此操作,将会很有帮助。谢谢。
猜你喜欢
  • 2021-04-27
  • 2022-12-18
  • 2021-08-22
  • 2020-07-25
  • 2021-06-11
  • 2022-01-20
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多