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

react-router-dom v6.4页面刷新/直接访问URL报错:页面未找到

React Router Dom 刷新/直接访问路径出现404问题解决方法

我的应用运行在http://localhost:8000,创建了NavBar组件,其中包含指向/home的Link。点击Link可正常跳转至/home,但刷新该页面或直接输入http://localhost:8000/home时会出现404错误。

依赖版本

"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.1",
"typescript": "^4.8.4"

错误截图

错误截图

相关代码

App.tsx

import { NavBar } from './components/NavBar'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'

export const App = () => {
  return (
    <div>
      <Router>
        <Routes>
          <Route path="/" element={<NavBar />} />
          <Route path="/home" element={<h1>Test React Router Dom</h1>} />
        </Routes>
      </Router>
    </div>
  )
}
import './navBar.style.scss'
import { Link } from 'react-router-dom'

export const NavBar = () => {
  return (
    <>
      <Link to={'/home'}>Link to Home</Link>
    </>
  )
}

index.tsx

import { createRoot } from 'react-dom/client'
import { App } from './App'

const container = document.getElementById('root') as HTMLElement

const root = createRoot(container)
root.render(<App />)

问题原因与解决方法

这个问题的核心是:BrowserRouter依赖前端路由机制,点击Link时是在前端完成路由跳转,不会向服务器发送请求;但刷新或直接输入URL时,浏览器会直接向服务器请求对应路径的资源,而服务器上并没有/home这个物理路由,因此返回404。

1. Create React App(CRA)项目场景

  • 方法一:在public目录下创建404.html,内容完全复制public/index.html,这样服务器返回404时会加载该文件,前端路由就能接手处理。
  • 方法二:使用serve工具启动构建后的项目,它会自动处理路由 fallback:
    # 全局安装serve
    npm install -g serve
    # 启动构建产物目录
    serve -s build
    
    -s参数会让所有请求都指向index.html,确保前端路由生效。

2. 自定义服务器(如Express)场景

在服务器代码中添加全局路由 fallback,让所有未匹配的请求都返回index.html:

const express = require('express');
const path = require('path');
const app = express();

// 托管静态资源
app.use(express.static(path.join(__dirname, 'build')));

// 所有请求都返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(8000);

额外优化:路由结构调整

当前路由中NavBar仅在/路径渲染,建议将其移至Routes外部,这样所有页面都能显示导航栏:

// 修改后的App.tsx
import { NavBar } from './components/NavBar'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'

export const App = () => {
  return (
    <div>
      <Router>
        <NavBar />
        <Routes>
          <Route path="/" element={<div>首页内容</div>} />
          <Route path="/home" element={<h1>Test React Router Dom</h1>} />
        </Routes>
      </Router>
    </div>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:20:47