How to use React BrowserRouter on the client and Java REST API (Spring Boot) on the server?

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

I can already request the server APIs through the path /api.

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

I don’t know Spring. Well booted, but I think I could check the server if the route does not match /api, after which I would return index.htmlwith all the reaction processing the logical data based on the route in the location of the HTTP request?

Hope I'm clear, I don't want the hash in the url and routing to be done on the client.

+6
source share
2 answers

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

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

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

0
source

Pretty old, but in general all you need to do is first combine the api and then have a wildcard to match everything else and return an index ...

Thus, any deep binding will still work, serving the root of your responsive application, where the router responds to the browser URL.

Spring - , @RequestMapping(value = "/"), , . , /api/, .

+1

Source: https://habr.com/ru/post/1016948/


All Articles