【问题标题】:locally host firebase backend with react frontend together, for debugging本地托管 firebase 后端和 react 前端,用于调试
【发布时间】:2021-05-17 00:07:01
【问题描述】:

我正在构建一个带有 Firebase 功能后端的 React 网站。

我正在使用 firebase serve 在本地托管我通过 express API 端点连接到我的 react 代码的 node.js 后端,并且我正在使用 react-scripts start 来测试我的 react 前端应用程序。

我的 react 应用程序中的所有 get 请求都使用 /some endpoint 与我的 firebase 本地服务器通信。但是它们在不同的端口上运行。 firebase 在 localhost:5000 上提供服务,而 react live 服务器在 localhost:3000 上提供服务。

我尝试了很多东西,但找不到任何有用的方法来完成这项工作。我最后将我的 react 项目添加为我的 firebase 项目中的子文件夹,并将 firebase.json 的托管公共路径添加到我的 react build 目录。它现在可以工作了,但我总是必须在每次更改时在我的 react 应用程序上运行 npm run build,以使其将我的应用程序编译到 build 目录中,这非常慢。

这样做的正确方法是什么?一起调试 react 应用和 firebase 后端。

【问题讨论】:

    标签: reactjs firebase debugging testing


    【解决方案1】:

    我终于使用cors 模块在我的服务器上启用了cross-origin-requests

    服务器端代码

    const cors = require("cors");
    
    
    app.get("/test", (req, res) => {
        return cors()(req, res, async () => {
            res.send("working...");
        });
    });
    

    服务器端代码

    然后在反应端添加一个简单的配置文件,在调试和部署测试之间切换真的很有帮助。

    config.js

    var domain = "";
    // domain = "http://localhost:5000";
    
    export {domain}
    

    然后,每当我在 react 中使用 apis 时,我只需注释/取消注释第二行即可在本地测试和部署测试之间切换。


    然后,每当我使用 API 时,我都会在所有引用中的每个 url 之前附加“域”,例如获取请求
    import { domain } from "config.js";
    
    fetch(domain + "/int-search", ...
    

    然后在我的 react 应用程序中使用 firebase servenpm start 在本地主机上运行 firebase 后端和 react 应用程序都可以正常工作。

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 2022-12-08
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2020-02-12
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多