首页 > 解决方案 > 从源“http://...”访问“https://...”处的 XMLHttpRequest 已被 CORS 策略(Spring Boot 和 Angular 7)阻止

问题描述

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

它抛出以下错误

从源“ http://localhost:4200 ”访问“ https://localhost:8082/Demo/list ”处的 XMLHttpRequest已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头出现在请求的资源。

客户端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-boothttp-postangular7same-origin-policy

解决方案


根据 Spring Security,您应该启用 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


推荐阅读