【问题标题】:How can I get rid of CORS error in Spring Boot with Angular? [duplicate]如何使用 Angular 消除 Spring Boot 中的 CORS 错误? [复制]
【发布时间】:2021-04-02 03:08:07
【问题描述】:

我在结合 Angular 的 Spring Boot 项目中遇到 CORS 问题。

我正在使用以下代码并将其注释为配置。

@Configuration
public class WebConfig {

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowedOrigins("http://localhost:4200");
      }
    };
  }
}

在 Angular 中我添加了这个:

不幸的是,我仍然收到此错误:

他们都没有完成这项工作。

【问题讨论】:

  • CORS 需要在服务器端进行管理,因此将这些标头客户端添加到您的请求不会有任何影响。
  • 尝试将 OPTIONS 添加到允许的方法中
  • 不,很遗憾没有。
  • Please don't post screenshots of text。它们无法被搜索或复制,并且可用性差。相反,将代码作为文本直接粘贴到您的问题中。如果选择它并单击{} 按钮或Ctrl+K,则代码块将缩进四个空格,这将导致其呈现为代码。

标签: angular spring-boot cors


【解决方案1】:

这实际上不是您的应用程序的问题,而是您的浏览器的问题。浏览器在发送实际数据之前向应用程序发出 OPTIONS 请求,以验证它们是否有权发出特定请求。

要让它运行,你可以在代码中添加 OPTIONS

@Configuration
public class WebConfig {

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS")
                .allowedHeaders("*")
                .allowedOrigins("http://localhost:4200");
      }
    };
  }
}

或使用CORS工具等扩展名。

【讨论】:

  • 不幸的是,两者都不起作用。我一直收到这个错误。
  • 尝试制作.allowedOrigins("*");
  • 完成,仍然卡在错误上。
  • 这是最后的希望,尝试将@CrossOrigin(origins = "*") 放在控制器类上
  • 这也没有解决问题。太奇怪了。我以前多次遇到过这个问题,通常你的一个答案解决了这个问题。这次不一样了。
猜你喜欢
  • 2021-11-09
  • 2022-10-07
  • 2020-02-07
  • 2021-11-06
  • 2019-08-26
  • 2020-09-13
  • 2021-03-31
  • 2020-11-05
  • 2022-07-05
相关资源
最近更新 更多