【问题标题】:Access at 'https://xxx' from origin 'http://localhost:8080/' blocked by CORS policy (No 'Access-Control-Allow-Origin' header present) error从源“http://localhost:8080/”访问“https://xxx”被 CORS 策略阻止(不存在“Access-Control-Allow-Origin”标头)错误
【发布时间】:2021-04-18 19:40:56
【问题描述】:

我目前正在本地测试我的应用程序(后端:springboot,前端:带有 axios 的 vue.js)并且我通过 PUT 请求收到此错误(我不知道它是 PUT 的事实是否是错误,但我测试的其他请求没有显示此错误)

我知道这是一个经常报告的错误,但我测试了我在互联网上找到的所有解决方案,但没有任何效果

我测试过:

在我的控制器上添加这个:

@CrossOrigin(origins = "*")

在产生错误的请求上添加同一行

改为添加:

 @CrossOrigin(origins = "http://localhost:8080")

在我的 cors 配置 bean 中添加这个:(这个实际上在其他请求上添加了新的 cors 错误)

 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

添加这个 bean

@Bean
public WebMvcConfigurer configurer(){
  return new WebMvcConfigurer(){
    @Override
    public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping("/*")
          .allowedOrigins("*");
    }
  };
}

在 axios 请求中添加此标头:

   { "Access-Control-Allow-Origin": '*' },

我承认我在这里有点迷路了。有人可以帮忙吗?

编辑:它是 PUT 的事实确实是错误的根源,即使我真的不知道为什么。但是如果我将其转换为 POST 请求,它就可以正常工作了

【问题讨论】:

  • 你从 curl 中得到了什么?
  • @k-wasilewski 没问题
  • 您确定没有截取代码中其他地方的响应吗?例如一些 jwt...
  • @k-wasilewski 我有一个 jwt 授权过滤器,我想问题可能来自那里,但我真的不知道如何

标签: spring spring-boot spring-security axios cors


【解决方案1】:

因此,在您的 JWT 相关类中查找任何拦截响应的内容并将其添加到那里:

response.setHeader("Access-Control-Allow-Origin", "*");

【讨论】:

    【解决方案2】:

    我不确定,但我也已经从 chrome 浏览器解决了 CORS 问题。 你应该检查 axios 和 vuejs 的代理配置。 当我配置代理时,它就解决了。

    HA 代理或一些负载均衡器可能是您需要访问的 https:// 前面的服务。

    【讨论】:

      【解决方案3】:

      将 @CrossOrigin(origins = "*") 添加到控制器对我也不起作用。 一直对我有用的是添加一个在每个请求上执行的过滤器。

      @Component
      public class Filter extends OncePerRequestFilter {
      
      
      @Override
      protected void doFilterInternal( HttpServletRequest request, HttpServletResponse 
      response, FilterChain filterChain )
              throws ServletException, IOException {
          response.addHeader( "Access-Control-Allow-Origin", "*" );
          response.addHeader( "Access-Control-Allow-Methods", "*" );
          response.addHeader( "Access-Control-Allow-Headers", "*" );
          filterChain.doFilter( request, response );
         }
      }
      

      【讨论】:

      • 是的,我已经有一个授权过滤器,我尝试向其中添加标题,但它不起作用
      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2019-08-09
      • 2021-03-27
      • 1970-01-01
      • 2021-02-20
      • 2020-11-26
      相关资源
      最近更新 更多