使用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 yourindex.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 yourpackage.json(for static hosting) or configure your server to serveindex.htmlfor 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')); });
- If you're using Create React App, add
二、访问/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/bestwith 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
BestItemscomponent 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
historyobject is configured to use hash mode instead of browser mode, the URL would look like/#/items/best—visiting/items/bestdirectly would not match and trigger the 404/redirect.
内容的提问来源于stack exchange,提问作者Tatiana
相关产品推荐
相关产品推荐

