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

Antd Pro带参数动态路由生产环境访问异常求助

带参数动态路由生产环境访问异常问题(Antd Pro + Umi 3)

路由配置(routes.ts)

export default [
  ...
  {
    path: '/board',
    name: 'Board',
    icon: 'DragOutlined',
    routes: [
      {
        path: '/board/:id',
        name: 'Board detail',
        icon: 'GroupOutlined',
        hideInMenu: true,
        component: './Board',
      },
    ],
  },
  ...

  {
    path: '/',
    redirect: '/welcome',
  },

  { component: './404' },
]

问题描述

  • 生产构建完成后,直接在浏览器地址栏输入/board/100(100为动态ID),会返回错误:Cannot GET /task-board/100
  • 页面内通过<a>标签跳转至/board/100可正常打开页面
  • 开发环境下无此问题,仅生产环境出现异常

项目依赖配置(package.json)

"dependencies": {
  "@ant-design/compatible": "^1.1.0",
  "@ant-design/icons": "^4.7.0",
  "@ant-design/pro-card": "^1.19.0",
  "@ant-design/pro-descriptions": "^1.10.0",
  "@ant-design/pro-form": "^1.64.0",
  "@ant-design/pro-layout": "^6.35.0",
  "@ant-design/pro-table": "^2.71.0",
  "@lexical/react": "^0.3.6",
  "@tinymce/tinymce-react": "^4.1.0",
  "@umijs/route-utils": "^2.0.0",
  "antd": "^4.19.0",
  ...
  "react": "^17.0.0",
  "react-dom": "^17.0.0",
  "react-helmet-async": "^1.2.0",
  "react-markdown": "^8.0.3",
  "umi": "^3.5.0"
}

解决方案

方案1:切换Umi路由模式为hashHistory

在项目根目录的.umirc.ts或config/config.ts中添加配置:

export default {
  ...
  history: {
    type: 'hash',
  },
  ...
}

此方式无需修改服务器配置,URL会变为/#/board/100形式,兼容性强,但URL会带有#符号。

方案2:配置服务器将所有请求 fallback 到index.html

若需保留browserHistory模式,需让服务器把所有路由请求转发到项目的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]
    
  • Express:在服务端代码中添加路由兜底
    const express = require('express');
    const path = require('path');
    const app = express();
    
    app.use(express.static(path.join(__dirname, 'build')));
    
    app.get('/*', function(req, res) {
      res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });
    
    app.listen(3000);
    

额外排查点

检查项目配置中是否设置了base路径,比如config.ts里的base: '/task-board/',若有则访问路径需要匹配该前缀,避免路径不匹配导致的404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:55:21