CORS 政策(Spring Boot 和 Angular 7)已阻止从源“http://..."访问“https://..."处的 XMLHttpRequest [英] 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 应用程序中,客户端发布功能无法调用服务器 Api 发布方法.
I am creating a sample application using Spring Boot and Angular 7. In spring boot I am converting http to https. In angular application the client side post functionality cannot call the server Api post method.
它抛出以下错误
在 'https://localhost:8082/Demo/list' 从源访问 XMLHttpRequest'http://localhost:4200' 已被 CORS 策略阻止:无 'Access-Control-Allow-Origin'请求的资源上存在标头.
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 Security,您应该启用 localhost 域以允许访问,或允许所有域访问(不安全)
As per Spring Security you should enable localhost domain to allow access, or allow all domain to access(not secure)
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
这篇关于CORS 政策(Spring Boot 和 Angular 7)已阻止从源“http://..."访问“https://..."处的 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!