部署到IIS后React应用程序路由无法正常工作

3
我是reactjs的新手,目前在IIS部署react应用程序时遇到了一些问题。
我执行npm run build,它生成了一个build文件夹,然后我将此文件夹复制到我的IIS中。当我浏览页面时,我能够看到空白页,但当我导航到测试路由时,它显示404。
我尝试在我的package.json中添加“homepage”:“/”或“homepage”:“。”但仍然相同。

index.html

enter image description here

这是我的构建结构。

enter image description here

任何帮助都会受到赞赏。

你的ReactJS应用程序的完整URL是什么?目前,它尝试从/static加载JS文件,这应该是你的IIS上的顶级“目录”。 - undefined
目前我在本地主机IIS上托管它,URL是localhost:6001。我尝试将主页放在'.'目录下,但JS文件将从./static加载。有没有办法去除斜杠? - undefined
当你点击它们的URL时,它确实会提供所有所需的JS文件吗? - undefined
当我在新标签页中打开JS文件时,我可以访问该JS文件。 - undefined
你的问题解决了吗? - undefined
@JalpaPanchal 是的,我会稍后分享解决方案。 - undefined
3个回答

5
无论何时您在生产环境中部署React页面,都会遇到这个问题。请参考此页面:https://inthetechpit.com/2019/06/13/handle-client-side-routes-with-iis-on-page-refresh-react-app/ 该问题出现在服务器端(不仅仅是IIS,而是所有服务器)。 您需要安装一个扩展程序,然后将配置文件添加到前端构建目录的路径中。
要安装的扩展程序在此处: https://www.iis.net/downloads/microsoft/url-rewrite 应放置在前端构建目录中的web.config文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
      <rules>
        <rule name="ReactRouter Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.html" />
        </rule>

      </rules>
    </rewrite>
</system.webServer>
</configuration>

1
您可以在public文件夹中创建web.config文件,然后将以下内容粘贴到其中,然后再次执行npm run build:
<?xml version="1.0"?>
<configuration>
<system.webServer>
  <rewrite>
     <rules>
        <rule name="React Routes" stopProcessing="true">
           <match url=".*" />
           <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
           </conditions>
           <action type="Rewrite" url="/" />
        </rule>
     </rules>
  </rewrite>
</system.webServer>
</configuration>

0

要在IIS中部署React JS应用程序,您可以按照以下步骤进行操作:

1)确保您已启用以下IIS功能:

最新版本的ASP.NET 静态内容 目录浏览

enter image description here

2) 以管理员身份打开命令提示符。进入React应用程序文件夹,然后运行以下命令:
npm run build

这将在您的应用文件夹中创建一个构建文件夹。

3)打开IIS,然后选择添加站点,并添加文件夹路径构建文件夹和站点绑定详细信息:

enter image description here

现在,浏览你的网站。

enter image description here

注意:确保将iis_iusrs和iusr权限分配给站点文件夹。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接