reactjs - 在 Servlet 环境中部署 React 应用程序

标签 reactjs servlets war

我需要在 servlet 环境中部署 React 应用程序作为部署在 tomcat 容器中的 war 。

到目前为止我执行的步骤:

1) 运行:> npm run build

2) 将构建目录的内容放在我的 war 下的 WebContent > dist 文件夹下,如下所示:

enter image description here

3) 在 WebContent 下添加了一个 index.html,重定向到 dist 文件夹内的索引:

<body onLoad="window.location.href='./dist'">

部署 war 时执行重定向,浏览器将我带到这个位置: http://localhost:8080/MyApp/dist/

但是页面出现错误:

enter image description here

(“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 ohave "."在 %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 时遇到问题:

enter image description here

注意事项

即使我手动编辑链接并尝试访问该站点,也没有错误,但没有显示任何内容!

如果我运行“serve -s build”(通常情况下,没有 war ),它会起作用!

最佳答案

在你的 React 项目中打开 package.json 文件

添加一个键值,即 "homepage":"./"。它看起来像

    {
  "name": "your-app-name",
  "version": "0.1.0",
  "private": true,
  "homepage": "./"
.
.
.
}

现在运行 => npm run build 并按照与您相同的步骤操作。

关于reactjs - 在 Servlet 环境中部署 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770197/

相关文章:

eclipse - 带有 Eclipse Juno 和 J2EE 预览服务器的简单 Servlet

java - 识别哪些 JSP 文件正在运行

java - 在 pom.xml 中使用 war 排除

java - 在 Spring Boot Web 应用程序中运行脚本

javascript - 每次刷新页面时如何加载用户?

javascript - 在 React Native 中嵌入 Python/C++ 代码?

javascript - super react ,无法读取未定义的属性 'call'

javascript - Reactjs 使用字符串的不同部分构建 url

java - 使用 javax.ws.rs.core.Application 实现通用 JAX-RS Web 服务

spring-boot - 如何在Jboss或Tomcat上部署Spring Cloud Gateway 2.1?