我需要在servlet环境中部署react应用程序,将其作为war部署到tomcat容器中。
到目前为止我所做的步骤:
1) ran:> npm run build
2)获取build目录的内容,放在war下的WebContent > dist文件夹下,如下所示:

3)在WebContent下增加了一个重定向到dist文件夹内索引的index.html:
<body onLoad="window.location.href='./dist'">在部署war时,会执行重定向,浏览器会将我带到这个位置:http://localhost:8080/MyApp/dist/
但是在页面中有错误:

(在"dist > static“文件夹下有到js文件的链接,但url不包括/MyApp/,因此找不到它们)
已经尝试过的内容:
1)点击此链接:https://www.megadix.it/blog/create-react-app-servlet/我尝试将BrowserRouter的基本名称设置为:
import {BrowserRouter as Router, Route, Switch, Redirect} from "react-router-dom";
ReactDOM.render(
<div>
{/*<Router basename={process.env.REACT_APP_ROUTER_BASE || ''}>*/}
<Router basename='/MyApp'>
<Switch>
<Route path="/" exact component={App} />
<Route path="/login" component={Login} />
<Route path="/customize" component={ProjectCustomize} />
{/*<Redirect path="*" to="/" />*/}
</Switch>
</Router>
{/*<Login />*/}
{/*<App/>*/}
</div>,
document.getElementById('root'));但是它并没有起作用!
2)遵循这个问题:https://github.com/coryhouse/react-slingshot/issues/397我编辑了我的public/index.html this“。在%PUBLIC_URL%之前:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href=".%PUBLIC_URL%/tdf.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href=".%PUBLIC_URL%/manifest.json" />似乎我通过了*.js文件加载错误,现在遇到了加载css的问题:

备注
即使我手动编辑链接并尝试访问该网站,也没有错误,但什么也没有显示!
如果我运行"serve -s build“(正常情况下,没有war),它就能工作!
发布于 2019-09-25 03:00:03
在react项目中打开package.json文件
添加键值,即“主页”:“./”。它看起来会像这样
{
"name": "your-app-name",
"version": "0.1.0",
"private": true,
"homepage": "./"
.
.
.
}现在运行=>、npm、run build并执行与您相同的步骤。
发布于 2019-09-20 08:05:17
解决此问题的最简单方法可能是将React文件直接移动到WebContent/文件夹下。让一个index.html重定向到另一个index.html是没有意义的。如果由于某种原因不能做到这一点,您可能需要配置Tomcat Context Root (假设版本8):https://tomcat.apache.org/tomcat-8.0-doc/config/context.html
您甚至可以将这些文件放在WAR之外,并正确配置您的上下文。这个blog page可能会给你一些很好的见解:
将上下文元素添加到主机元素中。Context有两个属性:docBase是磁盘上包含静态文件的目录,路径是您想要提供文件的URL。确保Tomcat有权读取docBase
中的文件
发布于 2019-09-26 22:52:06
1)这个问题基本上是与环境变量REACT_APP_ROUTER_BASE有关,因为它是未定义的:
<Router basename={process.env.REACT_APP_ROUTER_BASE || ''}>因此,如果它没有定义(我在pom.xml配置文件中配置了它,就像在获取解决方案的帖子中解释的那样,但似乎我遗漏了一些东西),在这种情况下,请使用硬编码的应用程序名称:
<Router basename={process.env.REACT_APP_ROUTER_BASE || '/MyApp'}>2)需要将此值添加到package.json:"homepage":"./“
否则,生成的index.html将使用相对路径,加载时将找不到脚本
3)不要使用window.location.href导航,而要使用this.props.history.push
https://stackoverflow.com/questions/57770197
复制相似问题