首页 > 解决方案 > CORS 策略错误 - 使用 Spring Boot + React 发现 api

问题描述

我正在尝试使用 Spring Boot 和 React 使用 spotify api 编写简单的应用程序。在 spring boot 站点中,我有一个很好的工作控制器:

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

}

在使用 main 方法的课堂上,我有 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);
            }
        };
    }

和我的安全课:

@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 错误:

访问 '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' 重定向)来自 'http://localhost:3000' 已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin' 标头存在请求的资源。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

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

标签: reactjsspring-bootcorsspotify

解决方案


尝试以下操作:

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

推荐阅读