我制作了一个 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/