React Router部署后直接访问路径出现404错误求助
React路由部署后直接访问路径404问题解决
问题详情
本地环境下访问/dashboard等路径完全正常,但部署到服务器后,直接在URL输入特定路径(比如/dashboard)会触发404错误。首次部署时功能正常,目前无法通过URL直接导航到对应页面,控制台报错:
Failed to load resource: the server responded with a status of 404 ()
相关代码片段:
index.js
const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <React.StrictMode> <BrowserRouter basename={process.env.PUBLIC_URL}> <Routes> <Route path="/" element={<App />}> <Route index element={<Home />} /> <Route path="sobre" element={<About />} /> <Route path="faq" element={<Faq />} /> <Route path="privacidade" element={<Privacy />} /> <Route path="termos" element={<Terms />} /> <Route path="quem-esta-no-app" element={<WhoIsInTheApp />} /> <Route path="privacidade/lgpd" element={<LGPDPage />} /> <Route path='dashboard' element={<DashboardHome />} /> <Route path="dashboard/login" element={<Login />} /> <Route path="dashboard/produtos/" element={<Products />} />pathName="/productCategoryUpdate" fields={[{ name: 'imageURL', type: 'file', accept: 'image/jpeg, image/png', label: 'Imagem', }, { name: 'Name', type: 'text', placeholder: 'Nome da categoria', },]} title="Categoria" />}/> <Route path="dashboard/produtos/medida" element={<MeasureList />} /> <Route path="dashboard/produtos/medida/criar" element={<MeasureCreate />} /> <Route path="dashboard/produtos/armazenamento" element={<StorageList />} /> <Route path="dashboard/produtos/armazenamento/update/:id" element={<Update pathName="/storages_update" fields={[{ name: 'imageURL', type: 'file', accept: 'image/jpeg, image/png', label: 'Imagem', }, { name: 'productStorageID', type: 'hidden', }, { name: 'Name', type: 'text', placeholder: 'Nome da categoria', },]} title="Armazenamento" />}/> <Route path="dashboard/produtos/armazenamento/criar" element={<StorageCreate />} /> <Route path="dashboard/produtos/avaliações" element={<ProductRating />} /> <Route component={PageNotFound} /> </Route> </Routes> </BrowserRouter> </React.StrictMode> </Provider> ); reportWebVitals();
App.js
function App() { const [isMobile, setIsMobile] = useState(window.innerWidth <= 768); const [isAuthenticated, setIsAuthenticated] = useState(false); useEffect(() => { checkUserAuthentication(); }, []); const checkUserAuthentication = async () => { try { await magic.user.isLoggedIn(); if (await magic.user.isLoggedIn()) setIsAuthenticated(true); } catch (err) { setIsAuthenticated(false); } }; const [theme, setTheme] = useState(getDefaultTheme()); const location = useLocation(); const currentPath = location.pathname.startsWith("/dashboard"); const isDashboardPath = currentPath; if (isDashboardPath) { return ( <ThemeContext.Provider value={{ theme, setTheme }}> <div className={`theme-${theme}`}> <div className="layout-wrapper"> { isAuthenticated ? ( <> <RespectiveNavbar isMobile={isMobile} theme={theme} handleThemeChange={handleThemeChange} setIsAuthenticated={setIsAuthenticated} /> <AsideMenu /> <Outlet /> </> ) : ( <Login setIsAuthenticated={setIsAuthenticated}/> ) } </div> </div> </ThemeContext.Provider> ); } else { return ( <ThemeContext.Provider value={{ theme, setTheme }}> <div className={`theme-${theme}`}> <div className="layout-wrapper"> <Navbar handleThemeChange={handleThemeChange} theme={theme} /> <Outlet /> <Footer /> </div> </div> </ThemeContext.Provider> ); } } const RespectiveNavbar = ({isMobile, theme, handleThemeChange, setIsAuthenticated}) => { return ( isMobile ? ( <Navbar handleThemeChange={handleThemeChange} theme={theme} /> ) : ( <NavbarDesktop handleThemeChange={handleThemeChange} theme={theme} setIsAuthenticated={setIsAuthenticated} /> ) ); } export default App;
解决方法
1. 服务器端配置(核心修复)
这是SPA使用BrowserRouter的典型问题:服务器收到/dashboard这类路径请求时,会去寻找对应物理文件,找不到就返回404。需要配置服务器,让所有路由请求都返回index.html,交给前端路由处理。
- Nginx:修改站点配置文件,添加:
location / { try_files $uri $uri/ /index.html; }
- Apache:在项目根目录创建或修改
.htaccess:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
- Netlify:创建
_redirects文件,内容:
/* /index.html 200
- Vercel:创建
vercel.json文件,内容:
{ "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }] }
2. 修复路由代码错误
你的路由配置存在语法错误,会导致路由解析异常:
dashboard/produtos/路由后面的代码混乱,Update组件的标签未正确嵌套,修复示例:
<Route path="dashboard/produtos/" element={<Products />} /> <Route path="dashboard/produtos/categoria/update" element={<Update pathName="/productCategoryUpdate" fields={[ {name: 'imageURL', type: 'file', accept: 'image/jpeg, image/png', label: 'Imagem'}, {name: 'Name', type: 'text', placeholder: 'Nome da categoria'} ]} title="Categoria" />} />
- 兜底404路由不符合React Router v6语法,改为:
<Route path="*" element={<PageNotFound />} />
3. 备选:改用HashRouter
如果无法修改服务器配置,可替换BrowserRouter为HashRouter,Hash模式路径带#(如/#/dashboard),服务器只会处理#前的路径,不会返回404:
import { HashRouter } from 'react-router-dom'; // 替换原BrowserRouter <HashRouter basename={process.env.PUBLIC_URL}> {/* 路由内容 */} </HashRouter>
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

