Christian Peters
Christian Peters

Reputation: 45

I cant make rest calls with react

I am learning to use React at the moment, and I have a problem: I want react to work with my Java Spring Boot backend (Tomcat). React is running on port 3000 (default) and my Tomcat server on port 8080 (default). Now, when I make a REST call, I get the following error

script.js:13 GET http://localhost:8080/api/path?p=test net::ERR_CONNECTION_REFUSED

My rest call looks like:

fetch('http://localhost:8080/api/path?p=test')
        .then(res => {
            console.log(res);
        });

What do I make wrong? I do not really have an idea.

Upvotes: 2

Views: 2989

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44665

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.

Upvotes: 8

Related Questions