An net::ERR_CONNECTION_REFUSED error is typically thrown when your frontend (React application) cannot connect to your backend (your Spring boot application). There are many possible reasons for this to happen, such as:
- Your back-end application is not running
- The path to your back-end application is not correct
- There is some kind of firewall between your front- and back-end application that is stopping the traffic
- ...
In your case it appeared to be the back-end application that was not running properly.
Your second problem is related to CORS, which is a mechanism that prevents JavaScript from connecting to other APIs/websites that are not on the same (sub)domain and port. In your case your frontend is running on a different port than you backend, so that means you have to deal with CORS.
To handle CORS, you have to add a header to your backend (namely the Access-Contol-Allow-Origin header the error is mentioning). With Spring, you can do that by adding the following annotation to your controller:
@CrossOrigin(origins = "http://localhost:3000")
Or you can configure CORS globally with a filter or using WebMvcConfigurer:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:3000");
}
};
}
As mentioned in the comments by @Lutz Horn, this is also described in a Spring guide.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.