Spring boot app return Access to XMLHttpRequest at “myURL” has been blocked by CORS policy

前端 未结 1 782
说谎
说谎 2021-01-27 16:46

i\'m stuck with this issue: i use a spring boot app in backend and angular app for the front, the issue is when i call a specific rest url in the backend that uses a jar depend

相关标签:
1条回答
  • 2021-01-27 17:01

    Firstly, you need add @CrossOrigin annotation in your controller. Than here is correct configuration from documentation:

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

    You can configure it your own way.

    Secondly, if you are using SpringSecurity you need add .cors() to your configuration.

    Example:

    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .cors().and()
                    .csrf().disable()
                    .authorizeRequests()
                    .anyRequest().permitAll()
                    .and().httpBasic();
        }
    
    0 讨论(0)
提交回复
热议问题