Home > Enterprise >  React can't get any response from spring boot after fetch request
React can't get any response from spring boot after fetch request

Time:12-07

I'm trying to fetch data from post request in react, but I can't get nothing back, the response it's ok and save the data in the database, after that I need to return a token in react but I can't understand why It does't work.

I tried a lot ot cros but nothing change.

Here the request in react:

 save(registerDTO) {
    fetch('http://localhost:8080/api/auth/register',{ method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': '*/*', 'Access-Control-Allow-Credentials': true},body: JSON.stringify( registerDTO )})
      .then(data => console.log(data)) 
      .catch(error=>console.warn(error))
  }

}

In the ispection on google chrome everything works but I can't see the response even on there

there isn't nothing in the response option.

This is my code on spring boot side:

@PostMapping("/register")
public ResponseEntity<Map<String,String>> registerHandler(@RequestBody RegisterDTO registerDTO) {
    log.info("User: {}",registerDTO);
    return ResponseEntity.ok(registerService.saveUser(registerDTO));
}

In postman everything work fine, I can't even get the error message in react.

I tried to add a lot of cors code:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000","192.168.1.7:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE"));
    configuration.setAllowedHeaders(Arrays.asList("*"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
//    @Bean
//    public WebMvcConfigurer corsConfigurer() {
//        return new WebMvcConfigurer() {
//            @Override
//            public void addCorsMappings(CorsRegistry registry) {
//                registry.addMapping("/**").allowedOrigins("http://localhost:3000/**");
//            }
//        };
//    }

//    @Bean
//    public CorsConfigurationSource corsConfigurationSource() {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
//        return source;
//    }

and I added this annotation in the restcontroller:

@CrossOrigin(origins = "http://localhost:3000")

CodePudding user response:

you missing:

.then(res=> res.json())

in your fetch code.

  • Related