Home > Back-end >  Request blocked by CORS policy in Angular frontent and Java Spring Boot backend?
Request blocked by CORS policy in Angular frontent and Java Spring Boot backend?

Time:03-19

updateStudent(userName: string, age: number): Observable<any> {
    debugger;
    let formData = new FormData();
    let reqJson: any = {};
    reqJson["userName"] = userName;
    reqJson["age"] = age;

    formData.append('info', JSON.stringify(reqJson));
    return this.httpClient.post(this.url   '/update-student', formData);
  }

... and I have this notation in my Java Spring Boot backend:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api")
public class HomeController {

This is an error that I get: Access to XMLHttpRequest at 'http://localhost:8080/api/update-student' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CodePudding user response:

You can use this code:

@Configuration
@EnableWebMvc
public class CourseConfig implements WebMvcConfigurer {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping("/**")
              .allowedOrigins("*")
              .allowedMethods("POST", "GET", "OPTIONS", "PUT", "DELETE")
              .maxAge(3600);
  }
}

CodePudding user response:

Go in your backend RestController and add the following as class level annotation

@CrossOrigin(value = {"http://localhost:4200"}, methods = {GET,POST,PUT,DELETE})
@RestController
@RequestMapping("/api")
public class HomeController {

Edit: The port 4200 is the one you need to allow.

  • Related