简体   繁体   中英

Angular/Spring with cors mapping added - blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

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,
    "password":password
});
}

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:

@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer{

    @Override
       public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("*")
                        .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

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

UPDATE

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",
                        "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")

and in angular

 this.httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json',
        'Access-Control-Allow-Origin':'*'})
      };

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

but doesn't work.

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

Example

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

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>(
    'localhost:9090/helios-admin/api/auth/login',
    { "username": username, "password":password },
    this.httpOptions
 );
}

You should add config to Spring to allow CORS

I made like this:

java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Kotlin

@EnableWebMvc
class WebConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
    }
}

Another ways for spring u can see here. Good luck

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

https://www.baeldung.com/spring-cors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Angular Socketio nodejs - blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Angular7 : has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Angular 13 : has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource keycloak-angular: Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Error in Angular 8 application with Solr 8.1.0 Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Access to XMLHttpRequest has been blocked by CORS policy. No 'Access-Control-Allow-Origin' header is present on the requested resource 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. how to fix it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM