Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React's BrowserRouter on 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 REST API, both client and server are packaged together so they are hosted on the same application server.

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

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

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?

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

like image 415
Karl.S Avatar asked May 03 '17 04:05

Karl.S


People also ask

How do I connect React to frontend with backend in Java?

Remember you need to put this in the React UI package. json file. With this in place, all the calls start with /api will be redirected to http://localhost:8080 where the Java API running. Once this is configured, you can run the React app on port 3000 and java API on 8080 still make them work together.

Can we use Reactjs with spring boot?

Introduction. In this tutorial, we'll learn how to create an application capable of creating, retrieving, updating, and deleting (CRUD) client data. The application will consist of a simple Spring Boot RESTful API and a user interface (UI) implemented with the React JavaScript library.


1 Answers

Quite old, but in general all you would need is to match api first, and then have a wildcard to match everything else and return index...

This way any deep linking would still work, by serving the root of your react app, where react router will pick up on the URL the browser holds.

Spring should handle something as simple as @RequestMapping(value = "/") as routing everything to index. I would expect if you specify /api/ it would be more specific and take precedence.

like image 161
TheNorthWes Avatar answered Oct 05 '22 23:10

TheNorthWes