如何在客户端使用 React 的 BrowserRouter,在服务器上使用 Java REST API (Spring Boot)? [英] How to use React's BrowserRouter on client and Java REST API (Spring Boot) on the server?

查看:67
本文介绍了如何在客户端使用 React 的 BrowserRouter,在服务器上使用 Java REST API (Spring Boot)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在客户端上使用 React,在服务器上使用 Java Spring Boot 来获取 REST API,客户端和服务器都打包在一起,因此它们托管在同一应用服务器上.

I want to use React on the client and Java Spring Boot on the server for REST API, both client and server are packaged together so they are hosted on the same application server.

我已经可以通过 /api 路径查询服务器 API.

I can already query the server APIs via the /api path.

但是(如何)我可以在客户端上使用 react-router-dom (Router v4) 的 BrowserRouter 而不是 HashRouter?

But (how) can I use the BrowserRouter of react-router-dom (Router v4) on the client instead of the HashRouter?

我不太了解 Spring Boot,但我想如果路由与 /api 不匹配,我可以在服务器上检查,然后我会返回 index.html 使用所有基于 HTTP 查询位置路径处理路由的反应逻辑?

I don't know Spring Boot well, but I guess I could check on the server if the route does not match /api, then I would return the index.html with all the react logic handling the route based on HTTP query location path?

我希望我清楚,我不希望 URL 中的哈希值和路由必须在客户端上完成.

I hope I am clear, I don't want the hash in the URL and routing must be done on the client.

推荐答案

我终于找到了如何捕获所有 GET 请求并返回我的 React 应用程序,非常简单,只需使用通配符 *, 注意 /* 将不起作用.

I finally found how to catch all GET requests and return my React app, it was deadly simple, just use a wild card *, note that /* will not work.

@Value("${server.servlet.context-path}")
private String contextPath;

@GetMapping("*")
public ModelAndView defaultPage(Map<String, Object> model) {
    model.put("contextPath", contextPath);
    return new ModelAndView("index", model);
}

在这个例子中,索引指向这个文件/src/main/resources/static/index.html

In this example, the index points to this file /src/main/resources/static/index.html

这篇关于如何在客户端使用 React 的 BrowserRouter,在服务器上使用 Java REST API (Spring Boot)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆