我的java spring后端中有一个@RestController:
@GetMapping(value = "/getItems")
public List<Item> getItems()
{
System.out.println("Requested!");
return itemRepository.findAll();
}
我正在尝试检索Angular前端中的项目,但出现以下错误:
Access to XMLHttpRequest at 'http://localhost:8080/api/getItems' from origin
'http://localhost:4200' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No 'Access-Control-
Allow-Origin' header is present on the requested resource.
但是我不确定为什么,因为我在Angular中添加了正确的标头:
getItems() {
this.http.get('http://localhost:8080/api/getItems',
{headers: new HttpHeaders({
'Access-Control-Allow-Origin': 'http://localhost:4200',
'Access-Control-Allow-Methods': 'GET, POST, PUT',
'Access-Control-Allow-Headers': 'Content-Type'
}
)})
.subscribe(
data => {console.log(data);
});
}
get请求确实可以在Postman中工作,但是我知道导致问题的原因是浏览器,并且要求提供“ Access-Control-Allow-Origin”标头,我已添加了该标头。 它可以编译,但似乎没有正确添加标头。有人知道这是怎么回事吗?
答案 0 :(得分:0)
哦,看来我可以在RestController中添加@CrossOrigins批注,并在后端指定一个原点!