【问题标题】:React JS Application links throwing Error 404 on live server but working on localhostReact JS 应用程序链接在实时服务器上抛出错误 404 但在本地主机上工作
【发布时间】:2021-10-19 08:34:16
【问题描述】:

我使用 create-react-app 构建了这个 react js 应用程序。我使用 react-router-dom 进行路由。当我直接访问任何链接时,例如 url/products 它将抛出 404 错误页面。但如果我从应用程序上的链接转到该页面,它将直接工作。但两种方式都在开发中完美运行。我只在生产时收到此错误。

它托管在 DigitalOcean 上

这是我的 app.js 设置:

<Router>
      <NavBar />
      <Switch>
        <Route exact path={`${process.env.PUBLIC_URL}/`} component={Home} />
        <Route path={`${process.env.PUBLIC_URL}/products`} component={Products} />
        <Route path={`${process.env.PUBLIC_URL}/category/:category`} component={Category} />

请帮忙看看我做错了什么并提出修复建议

【问题讨论】:

  • 您在package.json 中设置了proxy 吗?
  • 没有。我没有设置代理
  • 使用相对路径而不是提供PUBLIC_URL - 原因是react-router-dom 使用localhost 作为其基础,因此您作为path 传递的所有内容都与此相关。如果您在生产中,react 将使用您的公共 url 更新其基本 url
  • 这样吗? &lt;Route exact path="/products" component={Products} /&gt;
  • 没错。如果它解决了您的问题,我会将此评论转换为答案,以便您接受并关闭问题

标签: javascript reactjs react-router-dom digital-ocean


【解决方案1】:

我能够解决这个问题。问题不在于 React。它与 DigitalOcean 一起使用。

我必须通过这样做在 APP SPEC 中设置包罗万象

使用云面板 UI: 登录并点击应用程序>设置>>点击组件名称>向下滚动到自定义页面>编辑自定义页面并选择Catchall>在页面名称块中输入index.html>保存

【讨论】:

    【解决方案2】:

    使用以下代码添加 web.config 文件-

    <?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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多