【发布时间】:2020-05-25 06:11:38
【问题描述】:
我正在使用 Angular 和 Spring Boot 构建一个简单的 Web 应用程序,我对这两个框架都是全新的。我正在尝试使用 Angular HttpClient 发出 http GET 请求,但我遇到了这样的 cors 错误:
Access to XMLHttpRequest at
'http://127.0.0.1:8080/api/employees/all' from origin
'http://127.0.0.1:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我正在使用这样的角度代码:
this.http.get('http://127.0.0.1:8080/api/employees/all')
.subscribe(data => {
console.log(JSON.stringify(data));
});
但是当我开始遇到此错误时,我将其更改为:
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
this.httpOptions.headers.set('Authorization', 'Basic admin:admin123');
this.httpOptions.headers.set('Access-Control-Allow-Origin', '*');
this.httpOptions.headers.set('Access-Control-Allow-Method', 'GET, PUT, POST, DELETE, OPTIONS');
this.httpOptions.headers.set('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
this.http.get('http://127.0.0.1:8080/api/employees/all')
.subscribe(data => {
console.log(JSON.stringify(data));
});
但是这没有效果。我发现一些有类似问题的帖子,人们通过在 Spring Java 代码中添加 @CrossOrigin 注释解决了他们的问题,所以我也尝试了这个:
@CrossOrigin
@GetMapping(path = "/employees/all") // class @RequestMapping is "/api"
public @ResponseBody Iterable<Employee> getAllEmployees() {
System.out.println("endpoint reached");
return employeeRepository.findAll();
}
但这也不起作用。我不断收到同样的错误。我认为我没有完全理解问题的根源。这是服务器端问题还是客户端问题?另外我该如何解决这个问题?
感谢您为解决此问题提供的任何帮助。提前谢谢你。
【问题讨论】:
-
CORS 是服务器端问题。阅读有关它的文章,或an answer to one of the many questions we get about it a day。
标签: angular spring-boot http cors