node.js - 从服务器提供静态 React 应用程序,刷新时崩溃

标签 node.js reactjs express

我制作了一个 React 应用程序,它与我的 API 服务器托管在同一台计算机上,按照 this tutorial 的指导。 .

我的目录是这样设置的

- root
  - server.js (entry for the API server)
  - app (for all back-end stuff)
  - client (directory for React app)
    - public (static files used in the front-end)
    - src (for all front-end stuff)
    - build (directory containing static build)
      - index.html (entry for front-end)
      - ... (other bundled stuff)

我在下面的方法中提供了我的 React 应用程序的静态副本。

// server.js

const app = express();
if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));
}

app.use('/api', routes); // for API routes

我遇到一个问题,当我在本地启动它时(使用NODE_ENV=product),一切顺利并且页面刷新不会破坏应用程序。

但是,在我将其部署到 Elastic Beanstalk 后,页面刷新会破坏应用程序,并在浏览器中显示此 html 错误消息。

无法获取/{刷新之前我拥有的网址路径}

我可以在日志中看到浏览器尝试使用 GET/{url_pathname} 向服务器发送请求

我最初怀疑同时拥有 React 路由器和 Express 路由器会发生一些有趣的事情,但话又说回来,我很困惑为什么这与本地主机中的情况不一致。

最佳答案

如果您使用 NGINX,则需要更新位于以下位置的配置文件 /etc/nginx/sites-available

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

或者,如果您的应用程序不在默认目录中,例如“app-location”,您会得到这个。

location /app-location {
  root /var/www;
  index  index.html;
  try_files $uri $uri/ /app-location/index.html;
}

并重启nginx

sudo service nginx restart

关于node.js - 从服务器提供静态 React 应用程序,刷新时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753760/

相关文章:

javascript - 错误无法读取未定义的属性(读取 'configurations')。类型错误 : Cannot read properties of undefined (reading 'configurations' )

javascript - 如何从 React Native 应用程序向 Express 服务器发送请求?

node.js - node.js 上的 ClojureScript,代码

javascript - 使用 'nestjs/jwt' 签名动态/用户相关的 secret

javascript - Expressjs语言库

javascript - 替换 If/Else 链的更好方法

node.js - 特定 app.get 上的快速超时

javascript - 路由前检查 HTML 文件是否存在 [Angular JS/Node JS]

javascript - Electron 上的 react 路由器无法改变历史

javascript - ServiceWorker 注册失败 : The script has an unsupported MIME type - reactjs