【问题标题】:Can't serve React + Spring application无法提供 React + Spring 应用程序
【发布时间】:2023-03-14 02:33:01
【问题描述】:

最近尝试将我的 Spring + React 应用程序部署到 Heroku,但我遇到了问题。我做了什么:构建 React 应用程序,将 /build 目录的内容复制到 Spring 的 src/main/resource/static 文件夹中。然后当我在浏览器中打开localhost:8080 时,我得到了 Spring Security 默认登录页面。我使用以前的用户登录,当我再次访问 localhost:8080 时,我的 react 应用加载得很好。

然后我将这个.antMatchers( "/", "/api/test", "/api/me", "/api/register").permitAll() 添加到我的代码中,以便从我的前端删除登录页面,当我现在打开localhost:8080 时,我得到一个空白页面。但是当我登录时,React 页面再次加载正常。我尝试了以下方法:将反应应用程序文件放入 /templates 文件夹,没有运气。我尝试创建一个/webapp 文件夹并将文件放在那里,但没有运气。我尝试将server.servlet.context-path=/ 添加到我的application.properties,但不走运。我尝试这样创建一个重定向控制器:

@Controller
public class RedirectController {
    @GetMapping("/")
    public String getHomePage() {
        return "index.html";
    }
}

也没有运气。我尝试将我的安全设置更改为:.antMatchers( "/**", "/api/test", "/api/me", "/api/register").permitAll(),这确实有效,但问题是我的所有端点都暴露了,这是一个很大的禁忌。

另外我刚刚注意到我的 index.html 文件得到了正确的服务,但它没有加载和 javascript 或任何其他 React 文件。这是怎么回事??

【问题讨论】:

    标签: reactjs spring spring-boot spring-security


    【解决方案1】:

    哇哦.. 好的,我找到了解决方案,Spring Security 实际上阻止了对我的所有静态内容的访问,除了我的index.html。所有需要做的就是在这里添加/static/**.antMatchers( "/", "/static/**", "/api/test", "/api/me", "/api/register").permitAll(),让每个人都可以访问静态文件夹。可能需要对您拥有的任何其他静态文件执行相同的操作,例如不在 /static/ 文件夹中的图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2022-12-20
      • 2016-10-30
      • 2018-08-17
      • 2021-01-05
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多