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

React Router DOM问题:子目录路由显示空白页而非404页面

React Router多级路径404空白页问题解决

问题原因

访问example.com/asdfasdf/asdfasdf这类多级路径时出现空白页,控制台报Uncaught SyntaxError: Unexpected token '<',本质是静态资源路径错误:

  • 访问单级路径example.com/asdf时,浏览器请求的静态资源(如main.js)路径是example.com/main.js,服务器配置了回退到index.html,资源能正常加载,React Router可以渲染404页面。
  • 访问多级路径时,浏览器会以当前路径为基准请求资源(比如请求example.com/asdfasdf/asdfasdf/main.js),服务器找不到该资源,返回了index.html的内容,浏览器把HTML代码当成JS解析,就会出现语法错误,导致页面空白。

解决方案

1. 前端配置:确保静态资源使用绝对路径

  • 若为Create React App项目,在package.json中添加:

    "homepage": "/"
    

    打包后的资源引用会变成绝对路径(如/static/js/main.xxx.js),不受当前URL路径影响。

  • 若为Vite项目,在vite.config.ts中设置base路径:

    export default defineConfig({
      base: '/',
      // 其他配置...
    })
    

2. 服务器配置:所有路径回退到index.html

必须配置服务器,让所有不存在的文件/目录请求都返回index.html,这样React Router才能接管路由逻辑,正确渲染404页面。

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]

Express(Node.js)配置示例

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(3000);

代码说明

你提供的App.tsx和Index.tsx代码本身没有问题,Route path="*"已经正确配置了404路由,问题出在部署时的静态资源路径和服务器路由回退配置上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:33:21