从来源 'http://...' 访问 'https://...' 处的 XMLHttpRequest 已被 CORS 策略阻止(Spring Boot & Angular 7)

Access to XMLHttpRequest at 'https://...' from origin 'http://...' has been blocked by CORS policy(Spring Boot & Angular 7)

我正在使用 Spring Boot 和 Angular 创建示例应用程序 7. 在 spring boot 中,我正在将 http 转换为 https。在 angular 应用程序中,客户端 post 功能无法调用服务器 Api post 方法。

它抛出以下错误

Access to XMLHttpRequest at 'https://localhost:8082/Demo/list' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

客户端 Angular 7

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  firstClick() {
    return console.log('clicked');
  }
  getList() {
    return this.http.get('https://localhost:8082/Demo/list');
  }
}

客户端

  constructor(private data: DataService) {}

  ngOnInit() {
     this.data.getList().subscribe(data => {
       this.tempList = data
       console.log(this.tempList);
     });
  }

服务器

@CrossOrigin(origins = "http://localhost:4200")
@Controller

根据 Spring 安全性,您应该启用 localhost 域以允许访问,或允许所有域访问(不安全)

https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

已更新:

https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors

您必须启用本地主机域才能允许访问。然后创建一个它的bean。

public class CORSFilter extends GenericFilterBean implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Credentials", "*");
    httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
    filterChain.doFilter(servletRequest, servletResponse);

}

}

@Bean
public FilterRegistrationBean filterRegistrationBean(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean(new CORSFilter());
    registrationBean.setName("CORS FIlter");
    registrationBean.addUrlPatterns("/*");
    registrationBean.setOrder(1);
    return registrationBean;
}

这对我有用。谢谢

Spring 4.2.x CORS 文档提供了一个非常简单而优雅的解决方案。

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

这里是 link, https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/cors.html#_global_cors_configuration

尽管 Spring 5.1.x WebMvcConfigurerAdapter 已弃用,因此应使用 WebMvcConfigurer

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}