我正在使用create-react-app,它在我的本地运行良好,没有任何问题。当我将其部署在 IBM Cloud 上时,登录后,当我刷新页面时,它会给出 404 未找到错误 之前工作正常,不确定发生了什么。
我看到了很多相关的问题,我试图解决但没有解决的问题如下
1. 创建了 static.json
{
"root": "build/",
"routes": {
"/**": "index.html"
}
}
<强>2。我有这个设置
devServer: {
historyApiFallback: true,
contentBase: './',
hot: true
},
<强>3。我尝试在路由器周围添加,但没有成功
import React, { Component } from 'react';
import styled from 'styled-components';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
class App extends Component {
render() {
return (
<>
<Router>
<Switch>
<Route exact path="/" component={SignUp} />
<Route path="/some" component={Some} />
</Switch>
</Router>
</>
);
}
}
export default App;
<强>4。我尝试添加以下内容
import { HashRouter } from 'react-router-dom'
<HashRouter>
<App/>
</HashRouter>
这些似乎都不适合我。有什么建议
最佳答案
当将 build/
输出作为静态站点提供服务时,您必须将 nginx 配置为始终提供 index.html
(否则,它将尝试匹配 url静态文件夹/文件的路径,该文件夹/文件不存在)。有关此行为的更多信息可以在 create-react-app
docs 中找到。
如果您使用 nginx docker 镜像来为您的站点提供服务,则需要设置以下default.conf
:
server {
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location ~ ^/$ {
rewrite ^.*$ /index.html last;
}
listen 80;
server_name localhost;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
请注意 rewrite ^.*$/index.html
部分,该部分修改任何传入调用并提供 index.html
。
您的最小 Dockerfile
将如下所示:
FROM nginx
COPY default.conf /etc/nginx/conf.d/default.conf
COPY build/ /usr/share/nginx/html/
关于javascript - 使用 Nginx 在刷新 404 上部署后创建 React 应用程序中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53567077/