我已将 React 应用程序托管在 wwwroot/{myFolder} 内的 IIS 服务器上。我目前面临以下错误:
我已经在 wwwroot/{myfolder} 中有一个 web.config 文件,如下所示。
<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="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
我还安装了 URL 重写模块。
如果将 React Router 应用程序部署到服务器上的子文件夹,路由将会变得混乱。
例如,假设您有一个名为“my-app”的 React Router 应用程序,并且希望将其部署到服务器上的子文件夹“example”中。在开发环境中,您可以使用以下路由配置:
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
在开发环境中,React Router 可能会将
/about
解释为 http://localhost:3000/about
,而在部署到服务器的子文件夹时,React Router 可能会尝试将 /about
解释为 http://yourdomain.com/example/about
,这可能会导致路由不通匹配正确,导致混乱。
以下是我在这些情况下使用的两种解决方案。
解决方案1:
为了解决这个问题,你可以考虑使用路由配置中的basename属性来显式指定base URL:
<BrowserRouter basename="/example">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
通过设置basename,React Router在匹配路由时将使用正确的路径,无论是在开发环境中还是部署到服务器时的子文件夹中。
解决方案2:
实现这一点的最简单方法是使用 HashRouter 而不是 BrowserRouter。
<HashRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</HashRouter>
使用 HashRouter,您将在每个 URL 中包含 /#/(例如 http://yourdomain.com/example/#/about )。 在这种情况下,“example”子文件夹名称成为基本路径,哈希部分(#)后面的部分用于匹配React Router中的路由。这样做的好处是,无论您的应用程序部署到服务器的哪个子文件夹,都可以正确解析路由而不会混淆。
相关参考链接:
https://medium.com/@mateioprea/setting-up-a-react-app-with-react-router-in-iis-71cb86aee376