繁体   English   中英

获取 CORS 策略异常:请求的资源上不存在“Access-Control-Allow-Origin”header。 ReactJS/SpringBoot

[英]Getting CORS policy exception: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS/SpringBoot

好吧,这是我在浏览器中遇到的异常:

Access to XMLHttpRequest at 'http://localhost:8080/home/data' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

后端是 Spring 安全应用程序,前端是 ReactJS 应用程序。 在前端,我想向后端发送一个带有登录信息的 GET 请求。 这是前端的代码:

function make_base_auth(user, password) {
    var tok = user + ':' + password;
    var hash = btoa(tok);
    return 'Basic ' + hash;
}

export default class Login extends Component {

    

    getData() {
        $.ajax({
            type: 'GET',
            url: 'http://localhost:8080/home/data',
            dataType: 'json',
            //whatever you need
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', make_base_auth('fabian.graml@gmail.com', 'password'));
            },
            success: function(response){
                console.log(response)
            }
        });
    }

getData() function 在您单击页面上的文本时执行。

如前所述,后端是 Spring 引导应用程序。

这是我的SecurityConfiguration.java

@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    private final CustomUserService customUserService;

    @Bean
    public BCryptPasswordEncoder encodePasswd() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .authorizeRequests()
                .antMatchers("/home/**")
                .authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(new BCryptPasswordEncoder());
        provider.setUserDetailsService(customUserService);
        return provider;
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.addAllowedHeader("Access-Control-Allow-Origin");
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

这是我的CorsConfiguration.java

@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("**")
                        .allowedOrigins("**");

            }
        };
    }
}

我的问题:有人知道如何修复此异常或关闭 CORS 吗? 如果有人可以帮助我解决我的问题,那就太好了。

我认为您需要在 controller 中添加@CrossOrigin(origins = "*", maxAge = 3600)注释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM