I do have a react-application using BrowserRouter for routing between pages. I also have a Java Backend with Spring Boot.
When I start the backend and frontend seperataly with an applicationRunner and npm start the browserrouter works perfectly. For example http://localhost:3000/home works fine. And also localhost:8080/api/collection/{id} works fine with this code
Java-backend:
#RestController
#RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
public class ApiController {
#Autowired
private BeregningstjenestePoller poller;
#GetMapping("/collection/{id}")
public CollectionV2 withId(#PathVariable String id) {
return poller.getCollectionWithId(id);
}
React-frontend:
<BrowserRouter>
<Route exact path={'/'}>
<StartPage title={'Hello'} />
</Route>
<Route exact path={'/home'}>
<HomePage />
</Route>
</BrowserRouter>
But when I try to start the servers together with java -jar ./bapplication-main/target/beregning-oversikt-main-0-SNAPSHOT.jar the trouble starts.
The application is now running on localhost:8080, so the starting page works, but localhost:8080/home doesnt work anymore, but localhost:8080/api/collection/{id} still works.
My guess is some trouble with Spring Boot and React routing together, but I cant find an answer
Might the Route "/" is defined in both reactjs and spring boot.
So remove index method with "/" in spring boot IndexController, below method need to be removed.. it will work with React home page.
#Controller
public class IndexController {
#GetMapping("/")
public String index(Model model) {
return "index";
}
}
Related
I'm working on a full-stack app having spring boot v2.7.5 as the backend and Angular v15 as the front end. I use IntelliJ IDEA IDE for development. Locally, spring boot runs on http://localhost:8080 and angular runs on http://localhost:4200. I use Gradle to build the project a single war file and which would be deployed on an external tomcat server.
Following is the project structure:
I have 3 build.gradle files, 1 for frontend , 1 for backend, and 1 for global. When I run the global build.gradle file, it would call call build.gradle from fronend folder which builds angular project and copies all the build files and put them into backend/src/main/resources/static folder. Next, build.gradle from the backend gets called which would build the final war file to be deployed on the external tomcat server.
The reason I'm putting frontend build files (index.html, some .js files) into backend/src/main/resources/static is the fact that Spring Boot Serves static content from that location. more details .
So the static directory looks like this after adding frontend build files:
When I try to access http://localhost:8080, it loads index.html from the static folder.
So far it is good. When I click the login button, internally it calls the backend API and moves to the next page (home page i.e., http://localhost:8080/fe/appInstances).
Now if I refresh the page, it gives me the following 404 Whitelabel Error Page.
I understand that since this is spring-boot as it is looking for a definition of the http://localhost:8080/fe/appInstances API endpoint in the java code.
To fix this, I have created the following IndexController.java class which should redirect all the frontend rest endpoints to index.html which is present in main/resources/static folder.
IndexController.java
#Controller
public class IndexController {
#GetMapping("/")
public String index() {
return "redirect:/index";
}
#GetMapping("/fe/*")
public String anyFrontEndApi() {
return "index";
}
}
But now, I get the following Whitelabel error page about Circular view path [index]: would dispatch back to the current handler URL [/fe/index] again.
I have tried changing #Controller to #RestController and changing the return type to ModelandView or something like this. But irrespective of all, it is still giving me the Whitelabel Error Page about Circular view path...
#RestController
public class IndexController {
#GetMapping("/")
public String index() {
return "redirect:/index";
}
#GetMapping("/fe/*")
public ModelAndView anyFrontEndApi() {
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
return mv;
}
}
Am I missing something here? Can someone please suggest me a fix for this?
PS: #justthink addressed this situation here. But I don't know how to do reverse proxy way.
We had this situation of page refresh for Angular and Springboot and we resolved this by adding the below Configuration class extending WebMvcConfigurerAdapter
#Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**/*")
.addResourceLocations("classpath:/static/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
#Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
: new ClassPathResource("/static/index.html");
}
});
}
}
So basically, we are telling Springboot that if we have the resource, use the same if not then redirect it to index.html.
Now, to handle the path in Angular, it depends on how you would have written your routes. If the path is available, you show the page, if not, display 404 page.
Hope this helps.
Update 1:
WebMvcConfigurerAdapter is deprecated. If this causes any trouble, then instead of extending the class WebMvcConfigurerAdapter, you can implement WebMvcConfigurer
If you see the whitelabel error says that "this application has no explicit mapping for /error".
That means if no path is matched with the paths that are defined in controller mappings, it forwards the request to "/error" route. So we can override this default behaviour.
Spring provides ErrorController interface to override this functionality
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class CustomErrorController implements ErrorController {
#RequestMapping("/error")
public String handleError() {
return "forward:/";
}
}
I'm new to Spring Boot and I'm playing around with it trying to get a response from my backend.
The web server and application are running without errors but when I try to get "Hello World" by typing localhost:8080/api/hello I get a 404 not found.
This is the controller method
#RestController
#RequestMapping("/api")
public class EmployeeController {
#GetMapping("/hello")
public String greeting() {
return "Hello, World";
}
}
This is the response I get
the response
You've defined your api path as api/hello, but based on the screenshot of your request you are calling /hello.
use localhost:8080/api/hello ,
it will a solution for your problem
I hava Spring Boot Application.I want to show html.
index.html location is following
templete/view/index.html
Controller.java
#Controller
public class Controller {
#RequestMapping(value = "/view", method = RequestMethod.GET)
public String index() {
return "/view/index.html";
}
}
return "view/index";
Should be what you need. In the future you might consider saying what you expect to happen and what actually happens, even better providing an error message which might give a hint like your file could not be found.
I am using Jhipster(Angular + Springboot) Application for my existing project.
I managed to create a controller(app.resource) manually apart from the ones already generated by jhiptser(using .jh file) for achieving a file download functionality.
So, when we start the server we usually initiate two servers i.e gradlew and npm start. The second runs on port 9000 which eventually supports hot reload functionality.(front-end development)
So the problem is, I am able to access those endpoints from the server running on standard 8000 port. However, from the port which is a proxy(9000), the method is returning 404.
I tried to clean build the application several times.
NOTE: The #RequestMapping value on the new controller is different then those present already.
Does this have to do something with spring security?
Thanks in advance.
Here is the previous controller:
#RestController
#RequestMapping("/api")
public class FGAppDiagramResource {
#GetMapping(value = "/fg-app-diagram-downloadFile")
public void getImage(String fileName,String folderName, HttpServletResponse
response){
// Some Code
}
}
Here is my New controller:
#RestController
#RequestMapping("/fileDownload")
public class DownloadFileController {
private final Logger log =
LoggerFactory.getLogger(DownloadFileController.class);
public DownloadFileController() {
super();
}
#Autowired
private ApplicationProperties applicationProperties;
#GetMapping(value = "/fg-app-diagram-downloadFile/{fileName}/{folderName}")
public void getImage(#PathVariable String fileName,#PathVariable String folderName, HttpServletResponse response) {
// Some Code
}
}
Your new controller does not use /api so you must add your endpoint URL /fileDownload to proxy configuration of webpack dev server in webpack/webpack.dev.js
proxy: [{
context: [
/* jhipster-needle-add-entity-to-webpack - JHipster will add entity api paths here */
'/api',
'/fileDownload',
You may want to use /api/fileDownload to avoid changing proxy configuration and also because /api is useful for many other aspects like security and also using HTML5 URL routing strategy in Angular to get rid of # in client routes (see https://github.com/jhipster/generator-jhipster/pull/9098).
/api and /management are namespaces to avoid route conflicts, so it is usually wise to use them for your new endpoints.
I have a spring-boot application that has a few views set up. I also have bundled an Angular2 app. When I load the Angular2 app, all works fine, however, when I try to deep link to a route within the application, Spring MVC is intercepting the call, failing to find an associated view and returning the error page.
http://localhost:8080/index.html will load the Angular2 application which then re-writes the URL to be just http://localhost:8080/. If I then navigate to the route I want e.g. http://localhost:8080/invite/12345, then the route loads and works as expected. Hitting http://localhost:8080/invite/12345 directly returns the standard Spring MVC error page.
However, if I run the Angular2 app as a standalone application (not served up by spring-boot), then hitting that link directly works as expected. it loads the index.html, fires the route and shows me the data I want.
How can I, via Java configuration, tell Spring to ignore the /invite/** path (and other paths too as my Angular2 app grows) so I can deep-link to routes within my Angular2 application. Here's the current Java configuration:
#SpringBootApplication
#EnableResourceServer
public class AuthserverApplication extends WebMvcAutoConfigurationAdapter {
public static void main(String[] args) {
SpringApplication.run(AuthserverApplication.class, args);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/oauth/confirm_access").setViewName("authorize");
registry.addViewController("/success").setViewName("success");
}
#Bean
public ViewResolver getViewResolver() {
final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setSuffix(".html");
return resolver;
}
}
This project is inheriting from spring-boot 1.3.3.RELEASE:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
Based on your answer, I config like this and it's worked.
#RequestMapping(value = "/*", method = RequestMethod.GET)
#Override
public String index()
{
return "index";
}
#Override
#RequestMapping(value = "/login/*", method = RequestMethod.GET)
public String login()
{
return "redirect:/#/login";
}
So we can access to localhost:8080/angular-app/login/ without 404 error.
So the way I got round this in the end was to link directly to the index.html page so that it forced the angular2 app to load e.g.:
http://localhost:8080/index.html/#/invite/12345