添加了cors映射的Angular / Spring-被CORS策略阻止:所请求的资源上不存在“ Access-Control-Allow-Origin”标头

时间:2019-05-03 10:37:37

标签: angular spring spring-boot cors

我有一个简单的Angular应用,该应用通过以下方式向端点执行发布请求:

login(username:string, password:string){

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

但是抛出CORS策略错误。在我的Spring应用程序中,这是暴露端点的一种,我以这种方式设置了cors映射:

@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer{

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

}

我遇到了相同的问题,但是在另一个应用程序asked a question中,得到了响应并正确使用了它。现在,此角度项目无法正常工作。我需要更改一些东西吗?

编辑 这是我在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));
    }

更新

问题出在网址中:它需要一个'http://localhost:9090/helios-admin/api/auth/login',因此使用http。愚蠢的错误。
现在我有一个新的。
它说:

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

所以我添加了:

.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")

和成角度

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

但不起作用。

3 个答案:

答案 0 :(得分:0)

您可以尝试这样

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

答案 1 :(得分:0)

在其余api控制器类方法之前添加 @CrossOrigin 注释。

示例

@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
}

答案 2 :(得分:0)

您应该向 Spring 添加配置以允许 CORS

我是这样制作的:

java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

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

科特林

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

春天的另一种方式你可以在这里看到。祝你好运

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

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