【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource and JWT Token does not begin with Bearer String on put method请求的资源上不存在“Access-Control-Allow-Origin”标头,并且 JWT 令牌在 put 方法上不以 Bearer String 开头
【发布时间】:2021-09-24 05:24:33
【问题描述】:

我正在开发一个基于 Web 的应用程序,该应用程序带有 angular 和 spring boot。 Jwt 已生成,用户可以登录,他可以看到他的信息,但是当我想编辑用户信息时,它会在浏览器上显示此错误:

user:1 从源“http://localhost:4200”访问“http://localhost:8080/api/user”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应没有“ t 通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

在 IntelliJ 中,它说:JWT 令牌不以 Bearer String 开头

我用过: httpSecurity.cors().and().csrf().disable()

    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        config.setAllowCredentials(true);
        config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return source;
    }

在更新用户信息时仍然遇到问题。

【问题讨论】:

    标签: java angular spring spring-boot jwt


    【解决方案1】:

    在后端的相应Controller类中添加@CrossOrigin(origins = "*",allowedHeaders = "*")注解

    【讨论】:

      【解决方案2】:

      这是我的配置,你可以试试:

      @Configuration
      public class WebMvcConfig implements WebMvcConfigurer {
      
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              long MAX_AGE_SECS = 3600;
              registry.addMapping("/**")
                      .allowedOrigins("*")
                      .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
                      .maxAge(MAX_AGE_SECS);
          }
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-23
        • 2013-11-29
        • 2014-07-28
        • 2014-01-19
        • 2013-12-07
        相关资源
        最近更新 更多