React 路由器和 Apache + Nginx 给出意外的令牌 <

Yar*_*nko 3 apache nginx reactjs react-router react-router-dom

我有 React 网站,其中路由是使用react-router-dom 完成的,并且使用 localhost 一切正常。但在我的生产服务器上,无论我使用哪个 Web 服务器(Nginx 或 Apache2 或 Apache2 + Nginx)以及https://example.com/admin/list等嵌套链接,我都会收到错误:

Uncaught SyntaxError: Unexpected token '<'    2.a3028c0a.chunk.js:1
Uncaught SyntaxError: Unexpected token '<'    main.1b4093c1.chunk.js:1 
Manifest: Line: 1, column: 1, Syntax error.   manifest.json:1
Run Code Online (Sandbox Code Playgroud)

当您通过按钮转到嵌套链接时,一切正常。

 <NavLink to="/admin/asics">
Run Code Online (Sandbox Code Playgroud)

但刷新或直接进入后我收到此错误。

使用像https://example.com/admin这样的单个链接,一切都很好。

嵌套路由是如何完成的

应用程序.js

<BrowserRouter basename="/">
  <Switch>
    <Route exact path="/" component={Miners} />
    <Route path="/admin" component={Admin} />
    <Route path="/gratitude" component={Gratitude} />
    <Route path="/firmware" component={Firmware} />
    <Redirect to="/" />
  </Switch>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

管理.js

<BrowserRouter>
  <Switch>
    <Route exact path="/admin/asics" component={Panel} />
    <Route path="/admin/advertising" component={AdminImgPanel} />
    <Route path="/admin/statistics" component={AdminStat} />
    <Redirect to="/admin/asics" />
  </Switch>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

我想这可能是网络服务器的问题,所以我尝试了Apache2 和 .htaccess

RewriteEngine on 
# Don't rewrite files or directories 
RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^ - [L] 
# Rewrite everything else to index.html to allow html5 state links 
RewriteRule ^ index.html [L] 
Run Code Online (Sandbox Code Playgroud)

Nginx 在conf中也有这段代码

try_files $uri /index.html;
Run Code Online (Sandbox Code Playgroud)

两者的工作原理相同。

Yar*_*nko 5

问题出在package.json中,主页字段中是一个点

"homepage": "."
Run Code Online (Sandbox Code Playgroud)

你需要将其更改为斜杠

"homepage": "/"
Run Code Online (Sandbox Code Playgroud)