CORS 策略是您的浏览器提供的安全配置,这意味着它可以在任何其他浏览器上进行不同的处理。基本上,这意味着您的浏览器期待来自您的网站的关于如何处理对位于托管您网站的服务器/域之外的资源的请求的指令。
使用 HttpServletResponse 在后端设置此标头:
@GetMapping("/http-servlet-response")
public String usingHttpServletResponse(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "https://yourDomainHere.com");
return "This is the response with the new header";
}
另一个使用 ResponseEntity 的选项:
@GetMapping("/response-entity-builder-with-http-headers")
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "https://yourDomainHere.com");
return ResponseEntity.ok()
.headers(responseHeaders)
.body("Response with header using ResponseEntity");
}
您需要将“yourDomainHere.com”更改为您的 XMLHttpRequest 无法从中加载的实际域。
这是另一种方法。
实现 CORS 策略的现代浏览器将尝试通过向您尝试访问的 AJAX 请求的域放置额外的 HTTP 请求来调查是否允许 AJAX 调用。此预检请求将使用 OPTIONS 动词发送,如下所示:
OPTIONS /
Host: yourDomainHere.com 'you are going to'
Origin: http://www.yourWebsiteOriginalDomain.com 'you are going from'
Access-Control-Request-Method: PUT 'Any verb your XMLHttpRequest intends to use'
这允许您在后端配置映射以处理 OPTIONS 调用并使用以下自定义 HTTP 标头以类似的内容进行响应:
Access-Control-Allow-Origin: http://www.yourWebsiteOriginalDomain.com 'you are going from'
Access-Control-Allow-Methods: PUT, DELETE 'verbs that you allow'