spring-boot - 从源“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 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
推荐阅读
- javascript - 为什么 JavaScript Date 构造函数在这个数字上失败,但作为一种方法工作得很好
- kubernetes - 如何更改 Kubernetes 中运行的 Pod 限制?
- r - 拟合曲线时对参数施加条件
- apache-camel - Apache Camel:发送参数直接
- c# - 如何仅通过登录身份验证表单才能打开 exe 文件
- mongodb - 在 mongodb 中聚合查询结果
- c - C libcurl 小于预期的响应大小
- wcf - 无法使用凭据连接到远程 SOAP 服务
- mysql - Wordpress 数据库上的多个 Meta_Key 选择
- java - 使用 Solrj(查询和索引)