score:0
- here is an updated version of the controller previously posted:
@controller
public class reactappcontroller {
@requestmapping(value = { "/", "/{x:[\\w\\-]+}", "/{x:^(?!api$).*$}/*/{y:[\\w\\-]+}","/error" })
public string getindex(httpservletrequest request) {
return "/index.html";
}
}
score:9
i use a filter to forward requests to index.html if it's not a static resource or not an api call.
static resources are automatically served by spring boot if they are in /resources/static. i keep them in a specific folder /resources/static/rct for easy filtering. (i do not want headaches with regex)
index.html path to react app:
<script type="text/javascript" src="http://localhost:8080/rct/js/myreactapp.js"></script>
now the filter redirecttoindexfilter.java
@component
public class redirecttoindexfilter implements filter {
private final logger logger = loggerfactory.getlogger(this.getclass());
@override
public void dofilter(servletrequest request,
servletresponse response,
filterchain chain) throws ioexception, servletexception {
httpservletrequest req = (httpservletrequest) request;
string requesturi = req.getrequesturi();
if (requesturi.startswith("/api")) {
chain.dofilter(request, response);
return;
}
if (requesturi.startswith("/rct")) {
chain.dofilter(request, response);
return;
}
// all requests not api or static will be forwarded to index page.
request.getrequestdispatcher("/").forward(request, response);
}
}
controller to server index.html
@controller
public class appcontroller {
private final logger logger = loggerfactory.getlogger(this.getclass());
@getmapping(value = {"/", ""})
public string getindex(httpservletrequest request) {
return "/rct/index.html";
}
}
controller to server api calls
@restcontroller
public class projectcontroller {
private final projectservice projectservice;
public projectcontroller(projectservice projectservice) {
this.projectservice = projectservice;
}
@getmapping("/api/v1/projects/{id}")
public projectdata getproject(@pathvariable long id) {
projectservice.get(id);
...
}
so any call that is not api or static is forwarded to index. by forwarding you keep the url as needed by react router but forward to index.html
score:10
a simple approach that will send everything that isn't under api
to your react app is to create an api controller that uses regex:
import javax.servlet.http.httpservletrequest;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
@controller
public class reactappcontroller {
@requestmapping(value = { "/", "/{x:[\\w\\-]+}", "/{x:^(?!api$).*$}/**/{y:[\\w\\-]+}" })
public string getindex(httpservletrequest request) {
return "/index.html";
}
}
this controller simply redirects everything to index.html, allowing react and react-router to work its magic.
the regex works like this:
'/'
- matches root'/{x:[\\w\\-]+}'
- matches everything up to the second\
. eg.\foo
'/{x:^(?!api$).*$}/**/{y:[\\w\\-]+}'
- matches everything that doesn't start withapi
. eg.\foo\bar?page=1
Source: stackoverflow.com
Related Query
- how to work with react routers and spring boot controller
- How to connect docker-compose with react and spring boot
- How to package React front end with Spring Boot and run the executable jar?
- How to make react router work with static assets, html5 mode, history API and nested routes?
- How to integrate a React webapp inside a spring boot Application with jar packaging
- How to get React to work with Grunt and Babel?
- How to authenticate users with Social Login (Facebook, Google) in a REST API backend with Spring Boot (separate React Frontend)
- How do I apply SSL certs to my React app and Spring boot server?
- how does promise and useState really work in React with AWS Amplify?
- How to integrate Spring Boot with React
- Required request part 'image' is not present with React and Spring Boot
- Serve static folder with Spring Boot and React Router
- How to work with multiple checkboxes in react and collect the checked checkboxes
- How to get the simplest Material UI Select to work with React and Typescript?
- What is inline-rendering in React router and how does it work with "render" inside a route/
- Deploy war with Spring boot app and react app in Tomcat
- How to make infinite scroll work with react and intersection api while lazily fetching data?
- How do I get React to work with Babel and Gulp?
- How to post more than one object using React JS, Axios with a Spring boot backend?
- How to deploy Spring boot and React application together on GCP App Engine?
- How to make data fetching work together with Redux Toolkit and React Hooks?
- React and progress bar. How can I add progress bar that will work with my input and my data
- I deployed React and spring boot into 2 different applications on heroku. How can i make them talk to each other
- How to setup jest and puppeteer to work with a react app?
- React js and spring boot : axios error 400 with postmapping and two parameter
- How to test a className with the Jest and React testing library
- How to import CSS modules with Typescript, React and Webpack
- How to mock React component methods with jest and enzyme
- How to set up Babel 6 stage 0 with React and Webpack
- How do I store JWT and send them with every request using react
More Query from same tag
- Can't update React state hook from useEffect
- Single responsibility principle React refactor
- Pass a value from one component to another component in Gatsby
- How to Change Parcel Bundler's Compiled CSS Links' Order in the Compiled HTML
- How to toggle checkbox to change style to strikeoff using react
- Prevent state reset
- React Router Dom one route outside of nest
- Material-UI AppBar buttons collapse into each other on smaller screens
- how to set the default value for the input from a db in React
- I have an error with browserHistory and react-router
- User authentication in React Router
- Check if react-router path is active
- Owl Carousel data loads from an array in React Js
- Passing state in React from two different components
- How to combine inline style and external import const style in JSX React
- How to handle large sets of data response from an api fetch when no size/limit/count parameters are present for the api?
- React react-localize-redux translation inside HTMLelement-properties
- How to see if a user has clicked off a TextField in MUI
- bootstrap placing item in middle
- Import images in react in a loop
- How to use urls in React CSS inline styling without `$`?
- What is an in-memory API?
- Material-UI Theme stopped working Upgrading @material-ui/core & @material-ui/styles (REACT & Next.js)
- Cannot read property 'apply' of undefined Konva.js
- Auth0 async await return session user
- How to do state operations in function in react without class
- How to get the returned data from a smart contract function using ethers.js?
- React update API call having routing
- Function won't send Redux Dispatch after a Fetch Delete Request in React
- React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH