Firebase功能在Firebase托管React网站上不起作用

时间:2019-12-24 20:41:05

标签: firebase google-cloud-functions firebase-hosting

摘要

我正在尝试将已部署的Firebase功能用于正在使用React但目前无法正常工作的已部署Firebase托管站点。我在网站上使用Firebase功能所采取的步骤是将URL(https://us-central1-react-portfolio-f7e64.cloudfunctions.net/api/)设置为Firebase托管网站上package.json文件中的代理。

我希望接收的是发送照片信息列表的JSON数据。相反,当我到达API端点时,最终只能得到一个HTML文档作为响应。我认为这可能是错误的,因为我使用React.js作为前端。

尝试修复

之所以对此感到困惑,是因为当我在本地测试站点时将其设置为代理时,它可以正常工作并且可以访问API端点。

API调用

Firebase Hosted Site

 axios.get('/photos')
      .then(res => {
        console.log("Got Photos");
        console.log(res.data);

Firebase Functions

let functions = require("firebase-functions");
let admin = require("firebase-admin");
let app = require("express")();
admin.initializeApp();

let { getIntro } = require("./handlers/home");
const { getAllPhotos } = require("./handlers/photos");

app.get("/intro", getIntro);
app.get("/photos", getAllPhotos);   

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

handlers.js

exports.getAllPhotos = (req, res) => {
  console.log("Getting Photos");
  unsplash.users
    .photos("dchicchon")
    .then(res => res.json())
    .then(json => {
      console.log(json)
      res.json(json);
    });
};

要指定,我还使用了Firebase Blaze计划,该计划允许我使用第三方API。

非常感谢您提供任何反馈!预先感谢。

更新

因此,我意识到我需要通过此有用的视频(https://www.youtube.com/watch?v=a9MZOrFoPTY)更新axios baseURL以进行生产。但是,现在我遇到了cors问题:

Access to XMLHttpRequest at 'https://us-central1-react-portfolio-f7e64.cloudfunctions.net/api/photos' from origin 'https://react-portfolio-f7e64.firebaseapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

为了缓解这种情况,我用指定的配置更新了firebase.json:

"headers":[
      {
        "source":"**",
        "headers": [ {
          "key":"Access-Control-Allow-Origin",
          "value":"*"
        }]
      }
    ],

现在,我相信要将所有内容最终结合在一起,我需要以某种方式在firebase函数中使用cors来允许每个请求都被允许。那就是我目前被困住的地方。我正在阅读这篇文章(Enabling CORS in Cloud Functions for Firebase),但不确定在哪里使用cors。帮助吗?

最终更新

通过这篇有用的文章(https://codeburst.io/express-js-on-cloud-functions-for-firebase-f76b5506179),我能够发现如何在firebase函数中实现cors

这是我必须在Firebase函数中添加的内容: index.js

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

这是允许共享跨域资源的中间件,这样我就可以在Firebase托管站点上使用它。

0 个答案:

没有答案
相关问题