如何在 docker 中为 React 应用程序的部署配置获取基础 url?

How to configure fetch base url on deployment in docker for react app?

我有一个 React 应用程序,其中包含从 API 中提取的内容。我有一个可用的 dockerfile

如何为生产中的所有提取配置基础 url?

最后,我将在 Azure App Services 上部署我的 React 应用程序。 我在package.json中使用了标签proxy,但这只是为了开发。 示例提取如下所示:(在“/evaluations”之前必须放置基数 url)

    fetch(`/evaluations?onlyactiveones=true`, this.credentials)
        .then(response => response.text())
        .then(data => {
            this.setState({ evaluations: data });
            console.log(data);
        });

看起来您正在对亲戚 url 进行获取调用。所以默认情况下它会调用你的域作为基础 url。例如,在这种情况下,http://yourdomain.com/evluations, but most likely you want to make call to http://someotherdomain.com/api/evaluations。为此,您需要在您的 Azure 网站(或任何其他托管服务器)中配置反向代理

在 Azure 网站中,您可以按照以下建议配置反向代理 link: https://ppolyzos.com/2015/10/26/reverse-proxy-functionality-in-azure-web-sites/

我现在已经解决了这个问题。我做过的事情:

  1. 为基础 url 定义一个环境变量,例如:process.env.REACT_APP_API_PROXY
  2. 用这个环境变量替换所有提取。对于上面的例子:

        fetch(`${process.env.REACT_APP_API_PROXY}/evaluations?onlyactiveones=true`, this.credentials)
        .then(response => response.text())
        .then(data => {
            this.setState({ evaluations: data });
            console.log(data);
        });
    
  3. 随意定义环境变量。 env 变量必须在构建 React 应用程序之前放置,不能在运行时替换。