reactjs - 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 有更好的体验,可以帮助我吗?请
解决方案
尝试以下操作:
@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);
}
};
}
推荐阅读
- node.js - 如何将 NODE_SKIP_PLATFORM_CHECK 环境变量设置为 1 以跳过版本检查
- api - 地理服务器的用户接口
- javascript - 以角度 7 显示进度条以进行文件上传
- pytorch - 为什么 Pytorch 中用 group 参数实现的 depthwise_conv2d 比 Conv2d 慢?
- crud - 使用 modal 的 Laravel 8 crud 不向数据库添加数据
- sql - 运算符在 SQL 中被视为变量
- java - 在 Java 中向 Microsoft Graph 客户端添加代理设置
- php - 无法使用 sqlite 运行迁移
- javascript - 未捕获的类型错误:无法设置只有一个 getter 的 # 属性树
- pine-script - 管理多头和空头订单,例如 LucF PineCoders Backtesting-Trading Engine