1
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.

Hrvoje T
  • 3,365
  • 4
  • 28
  • 41
  • You can find your answer in this [link](https://www.baeldung.com/spring-cors) – Mohammad Javad Mar 18 '22 at 19:05
  • I followed that. You can see I have already needed notation – Hrvoje T Mar 18 '22 at 19:17
  • @HrvojeT, can you reach this endpoint with postman? If not then it is a common issue that if this endpoint is not registered into servlet from spring by some false configuration, then spring will also reply with cors error, when you try to reach it from outside. Please check if endpoint is accesible in general for ex from postman – Panagiotis Bougioukos Mar 18 '22 at 21:15
  • 1
    It seems like adding `.and().csrf().disable()` to my configuration allowed POST method .. don't know why? Found it here https://stackoverflow.com/questions/50486314/how-to-solve-403-error-in-spring-boot-post-request – Hrvoje T Mar 19 '22 at 23:40
  • 1
    Yes, CSRF may occur when you're trying to send a post request from a web application. To, prevent that from happening, a CSRF token is sent along with each post/put/patch request for extra security. If you're using spring-security it's by-default behavior. To by-pass that csrf().disable() is used – Subham Mar 21 '22 at 17:03

1 Answers1

0

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);
  }
}