我正在嘗試使用Spring Boot和React撰寫帶有Spotify api的簡單應用。 在Spring Boot站點中,我有一個作業良好的控制器:
@RestController
@CrossOrigin()
public class SpotifyTopArtistClient {
@GetMapping("/artist"/span>)
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()。
}
在有主方法的類中,我有豆子:
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**"/span>)
.allowedOrigins("http://localhost:3000")
. .allowedMethods("GET"/span>, "POST"/span>, "PUT"/span>。"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/*"/span>).authenticated()。
http.cors().and().csrf().disable()。
}
當我在瀏覽器和postman中測驗端點http://localhost:8080/artist,它與我預期的一樣。
在react方面,我有代碼:
componentDidMount(){
fetch('http://localhost:8080/artist'/span>)
.then(response => response.json()
.then(data=> {
console.log(data)
})
}
當我試圖運行這個時,我看到政策-CORS錯誤:
從'https://accounts.spotify.com/authorize?client_id=8c8db951b0614847b5faf36b300fcb07&redirect_uri=http://localhost:8080/login&response_type=code&scope=user-read-private user-read-email user-top-read&state=vpHQLG'(從'http://localhost:8080/artist'重定向)獲取的權限被CORS策略阻止了。請求的資源上沒有'Access-Control-Allow-Origin'標頭。如果不透明的回應符合您的需求,請將請求的模式設定為 "no-cors",以便在禁用 CORS 的情況下獲取資源。為什么在SpotifyTopArtistClient類上面添加CrossOrigin的注解,卻沒有起到這個作用? 也許有人對Spotify api有更好的經驗,可以幫助我? 拜托了
。uj5u.com熱心網友回復:
請嘗試以下方法:
。
public class SpotifyTopArtistClient {
(...)
}
現在更新WebMvcConfigurer:
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**"/span>)
.allowedOrigins("http://localhost:3000")
. .allowedMethods("GET"/span>, "POST"/span>, "PUT"/span>。"DELETE", "HEAD", "PATCH", "OPTIONS")
.allowCredentials(true)。
}
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/332560.html
標籤:
