CORS 策略错误 - spotify api with Spring boot + React

CORS policy error - spotify api with Spring boot + React

我正在尝试使用 Spring Boot 和 React 编写带有 spotify api 的简单应用程序。 在 spring 引导站点中,我有一个运行良好的控制器:

@RestController
@CrossOrigin()
public class SpotifyTopArtistClient {


    @GetMapping("/artist")
    public SpotifyArtist getTopArtist(OAuth2Authentication details){
        String jwt = ((OAuth2AuthenticationDetails)details.getDetails()).getTokenValue();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization","Bearer "+jwt);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);

        ResponseEntity<SpotifyArtist> 
        exchange=restTemplate.exchange("https://api.spotify.com/v1/me/top/artists? 
        time_range=medium_term&limit=1&offset=0", HttpMethod.GET,httpEntity,SpotifyArtist.class);


        return exchange.getBody();
    }

}

在 class 的主要方法中,我有 bean:

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

还有我的保安class:

@Configuration
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/test").authenticated();
        http.authorizeRequests().antMatchers("/artist").authenticated();
        http.authorizeRequests().antMatchers("/login").authenticated();
        http.authorizeRequests().antMatchers("/login/*").authenticated();
        http.cors().and().csrf().disable();
    }
}

当我在浏览器和邮递员中测试端点 http://localhost:8080/artist 时 - 它按预期工作。

在反应方面我有代码:

  componentDidMount(){

    fetch('http://localhost:8080/artist')
    .then(response => response.json())
    .then(data=>{
      console.log(data)
    })
  }

当我尝试 运行 时,我看到 policy-CORS 错误:

从来源 'http://localhost:3000' 在 'https://accounts.spotify.com/authorize?client_id=8c8db951b0614847b5faf36b300fcb07&redirect_uri=http://localhost:8080/login&response_type=code&scope=user-read-private%20user-read-email%20user-top-read&state=vpHQLG'(从 'http://localhost:8080/artist' 重定向)获取的访问已被 CORS 策略阻止:否 'Access-Control-Allow-Origin' header 出现在请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为 'no-cors' 以在禁用 CORS 的情况下获取资源。

为什么在 SpotifyTopArtistClient class 上面添加注释 CrossOrigin 不起作用? 也许有人对 spotify api 有更好的体验,可以帮助我吗? 请

尝试以下操作:

@RestController
public class SpotifyTopArtistClient {
  (...)
}

现在更新 WebMvcConfigurer:

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