React生产构建部署Tomcat后新窗口URL找不到问题求助
问题分析与解决方案
你遇到的核心问题是路径拼接错误:部署到Tomcat后,项目的上下文路径是/sbfrontapp,但你打开新窗口时用的是/sb-user-component,这个路径会直接指向Tomcat服务器的根目录(而非你的项目目录),所以导致页面未找到。
修复步骤
1. 修正新窗口的跳转路径
不要直接写硬编码的绝对路径,而是结合React Router的配置来拼接正确路径:
方案一:类组件结合withRouter
给TreeView组件包裹withRouter,获取路由上下文里的basename:
import { withRouter } from 'react-router-dom'; class TreeView extends PureComponent { onNodeClick = (node) => { if (node.isLeaf) { const cmdText = node.value.split("_")[1].toUpperCase(); if (cmdText) { // 从props中获取basename,拼接完整路径 const fullPath = `${this.props.history.createHref({ pathname: '/sb-user-component' })}`; let opts = "width=900,height=600,toolbar=no,scrollbars=no,location=no,resizable=no"; window.open(fullPath, "new-tab", opts); } } }; // ... 其余代码 } // 用withRouter包裹组件 export default withRouter(TreeView);
方案二:直接复用Router配置的basename
如果不想用withRouter,可以直接复用app.js里的basename值拼接路径:
class TreeView extends PureComponent { onNodeClick = (node) => { if (node.isLeaf) { const cmdText = node.value.split("_")[1].toUpperCase(); if (cmdText) { const basename = "/sbfrontapp"; const fullPath = `${basename}/sb-user-component`; let opts = "width=900,height=600,toolbar=no,scrollbars=no,location=no,resizable=no"; window.open(fullPath, "new-tab", opts); } } }; // ... 其余代码 }
2. Tomcat额外配置(防止SPA路由刷新404)
如果后续遇到刷新子路由也出现404的情况,需要在项目的WEB-INF目录下创建web.xml,添加404转发规则:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <error-page> <error-code>404</error-code> <location>/index.html</location> </error-page> </web-app>
这样Tomcat会把所有404请求转发到React的入口页面,由React Router处理路由。
内容的提问来源于stack exchange,提问作者Md. Imran Hasan
相关产品推荐
相关产品推荐

