I have a simple Angular app that perform a post request to an endpoint this way:

login(username:string, password:string){

   return this.http.post<String>('localhost:9090/helios-admin/api/auth/login',{
    "username": username,

but the error of CORS policy is thrown. In my Spring application, that is the one the expose the endpoint, I've set the cors mappings this way:

public class MyWebMvcConfig implements WebMvcConfigurer{

       public void addCorsMappings(CorsRegistry registry) {
                        .allowedMethods("GET","POST", "OPTIONS");


I've encountered the same problem but with another application, asked a question, got the response and used it correctly. Now with this angular project it doesn't work. Do I have to change something?

EDIT This is my controller in Spring Boot

    @ApiOperation("Login into Helios administrational console.")
    public ResponseEntity<?> autenticate(@Valid @RequestBody LoginRequest request) {
        Authentication auth = authManager
                .authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        String token = jwtProvider.generateToken(auth);
        return ResponseEntity.ok(new JwtAuthResponse(token));


The problem was in the url: it wanted a 'http://localhost:9090/helios-admin/api/auth/login', so with http. Stupid error.
Now I have a new one.
It says:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So I've added:

.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")

and in angular

 this.httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json',

   return this.http.post<String>('http://localhost:9090/helios-admin/api/auth/login',{
    "username": username,
}, this.httpOptions).pipe(catchError(this.errorHandler));

but doesn't work.

2 Answers

Yash Rami On Best Solutions

You can try like this

public httpOptions;

login(username:string, password:string){
 this.httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': <some data> })

   return this.http.post<String>(
    { "username": username, "password":password },
Shalika On

Add @CrossOrigin annotation before the rest api controller class method.


@RequestMapping(value = "/login", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseBean> postUserLogin(@RequestBody LoginDTO loginDTO) {