【问题标题】:React app with nginx not switching components when using router使用路由器时使用 nginx 反应应用程序不切换组件
【发布时间】:2019-11-06 14:52:39
【问题描述】:

我正在尝试使用 nginx 部署我的 react 应用程序。

我遇到的问题是在更改路线时,例如/about 它实际上并没有更新前端,它只是保留在索引上。

这是我在可用站点中的配置:

server {
  listen 80 default_server;
  server_name server_ip_here;
  root /sites/FrontEnd/React/build;
  index index.html;

  access_log /var/log/nginx/krim.com.access.log;
  error_log /var/log/nginx/krim.com.error.log;

  location / {
      try_files $uri /index.html;
  }
}

这是路由器:

import {Redirect, BrowserRouter as Router,Route,Switch} from 'react-router-dom';

<Router>
      <CookieConsent buttonText="Accept">
      </CookieConsent>

      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/About" component={Over}/>
        <Route path="/FAQ" component={FAQ}/>
      </Switch>

</Router>

现在,页面索引加载,但使用 nginx 时转到 my-ip/About 或 my/FAQ 没有任何作用。

现在使用npm start 一切正常,此外使用serve -s build 也可以正常工作,所以这似乎是我的一些 nginx 配置错误。

感谢您的帮助,干杯。

编辑: 更正,本地serve 确实有效,但在远程虚拟机上也无效。

【问题讨论】:

  • 因为这个 SPA 应用程序 nginx 提供索引 html 来获取您的 javascript。一旦 JS 被加载并执行,路由就在客户端完成。根据您的 nginx 配置,我看到您缺少应该为 JS 服务的路由。你的控制台说什么?
  • @Maielo 我没有收到任何控制台错误。

标签: javascript reactjs nginx react-router


【解决方案1】:

您是否尝试在自己的机器上而不是在虚拟机上构建它(假设您使用的是虚拟机)?

【讨论】:

    【解决方案2】:

    我在自己的电脑上构建了这个包,然后上传到了虚拟机,现在它可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 2019-11-14
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多