如何在IIS子目录中部署React App

问题描述 投票:0回答:1

我有一个 React 应用程序,需要将其部署在 IIS 子目录中。我怎样才能做到这一点?我尝试过,但它显示空白屏幕。当我从 VS code 运行它时,它运行良好。

reactjs visual-studio-code iis deployment subdirectory
1个回答
0
投票

您描述的太简单了,我们不知道您是如何将React应用程序部署到IIS子目录的。

您可以参考此线程中的步骤在 IIS Web 服务器中托管 React 应用程序。

我如何在 IIS Web 服务器中托管 React 应用程序?

但是需要注意的是,如果你将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

https://muffinman.io/blog/react-router-subfolder-on-server/

© www.soinside.com 2019 - 2024. All rights reserved.