You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-router-dom访问页面及/items/best时出现404的原因分析

分析react-router-dom中的两个404问题

Hey there! Let's dig into the two 404 errors you're hitting with react-router-dom, using your provided route setup as a starting point:

<Router history={history}>
  <Switch>
    <Route exact path="/items" component={Items} />
    <Route exact path="/items/best" component={BestItems} />
    <Route exact path="/login" component={Login} />
    <Redirect from="*" to="/login" />
  </Switch>
</Router>

一、通过框架获取页面时出现404

This almost always boils down to server-side routing misconfiguration for single-page applications (SPAs) using browser history mode. Here's why:

  • When you use react-router-dom's browser history (instead of hash history), direct URL entries or page refreshes send a request to your server for that specific path (e.g., /items). If your server isn't set up to redirect all non-existent routes to your index.html (where your React app lives), it'll return a 404 because the server doesn't recognize that path as a static file or server route.
  • Fixes to try:
    • If you're using Create React App, add "homepage": "." to your package.json (for static hosting) or configure your server to serve index.html for all routes.
    • For Nginx, add this to your server block:
      try_files $uri $uri/ /index.html;
      
    • For Express.js, add a catch-all route:
      app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
      });
      

二、访问/items/best时触发404

Looking at your route setup, the /items/best route should match when you visit that path, but here are the most likely culprits:

  • Using <a> tags instead of <Link> components: If you're navigating to /items/best with a standard <a href="/items/best"> tag, this will trigger a full page refresh. Without the server-side config mentioned above, this will result in a 404. Always use react-router-dom's <Link to="/items/best"> for client-side navigation.
  • Typos or path mismatches: Double-check that your navigation links are pointing to exactly /items/best (no extra slashes, case sensitivity issues—URLs are case-sensitive!).
  • Component import issues: Make sure the BestItems component is properly imported into the file where your routes are defined. A missing or incorrect import could cause the route to fail silently, leading to the redirect to /login (since the * catch-all redirect would kick in if the route doesn't render anything).
  • History mode conflicts: If your custom history object is configured to use hash mode instead of browser mode, the URL would look like /#/items/best—visiting /items/best directly would not match and trigger the 404/redirect.

内容的提问来源于stack exchange,提问作者Tatiana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:42:40