繁体   English   中英

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

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

我有一个简单的 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");
       }

}

我遇到了同样的问题,但在另一个应用程序中, 提出了一个问题,得到了响应并正确使用了它。 现在有了这个 angular 项目,它就行不通了。 我必须改变什么吗?

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

更新

问题出在 url 中:它想要一个'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));

但不起作用。

在rest 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
}

你可以这样试试

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

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

我是这样制作的:

爪哇

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM