我有 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
当您通过按钮转到嵌套链接时,一切正常。
<NavLink to="/admin/asics">
但是在刷新或直接进入后我得到了这个错误。
使用单个链接,如 https://example.com/admin一切正常。
嵌套路由是如何实现的
App.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>
Admin.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>
我在想这可能是网络服务器的问题,所以我尝试了 Apache2 with .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]
还有 在 conf 中使用此代码的 Nginx
try_files $uri /index.html;
两者的工作原理相同。
最佳答案
问题出在 package.json,其中 homepage 字段是一个点
"homepage": "."
你需要把它改成斜线
"homepage": "/"
关于reactjs - React 路由器和 Apache + Nginx 给出意外 token <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69235005/