如何在使用纯 JavaScript 的 AJAX 调用中设置 CORS 标头,这会影响其他休​​息服务?

Posted

技术标签:

【中文标题】如何在使用纯 JavaScript 的 AJAX 调用中设置 CORS 标头,这会影响其他休​​息服务?【英文标题】:How to set CORS header in an AJAX call with pure JavaScript that is hitting other rest service? 【发布时间】:2017-04-08 00:42:14 【问题描述】:

我有以下在 html 页面加载时调用的 JS 函数。当页面加载时,我在 Firefox 控制台日志中看到以下错误。

Firefox 控制台日志:

"NetworkError: 403 Forbidden - http://localhost:8080/publicKey/lookup/TRUUS2"
TRUUS2
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/publicKey/lookup/TRUUS2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

publickey.js

function loadPublicKey() 

    var xmlhttp = createCORSRequest('GET', 'http://localhost:8080/publicKey/lookup/TRUUS2');
    xmlhttp.send();

    xmlhttp.onreadystatechange = function () 
        if (this.readyState === 4 && this.status === 200) 
            alert(this.responseText);
            document.getElementById("keyDiv").innerHTML = this.responseText;
        
    ;



function createCORSRequest(method, url) 
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) 
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.open(method, url, true);
     else if (typeof XDomainRequest != "undefined") 
        // Otherwise, check if XDomainRequest.
        // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
        xhr = new XDomainRequest();
        xhr.open(method, url);
     else 
        // Otherwise, CORS is not supported by the browser.
        xhr = null;
    
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
    return xhr;

我已经添加了 xhr.setRequestHeader("Access-Control-Allow-Origin", "*") 语句来修复 CORS 问题,但没有运气。我正在寻找纯 JS 实现。

注意:我可以通过 Postman 成功点击http://localhost:8080/publicKey/lookup/TRUUS2 URL 并获得响应。没有问题。

不知道我错过了什么。请指导。

【问题讨论】:

您误解了 CORS 的工作原理。您不要将标头放在请求上 - 它需要放在 response 上。你需要修改你的服务器端代码。 谢谢罗里,你是对的。在下面用我的答案更新了这篇文章。 【参考方案1】:

根据 Rory 提供的输入,我从 JS 中删除了 xhr.setRequestHeader("Access-Control-Allow-Origin", "*") 并在我的控制器中添加了 sn-p @CrossOrigin(origins = "http://localhost:8084") 并解决了问题。

@CrossOrigin(origins = "http://localhost:8084")
@RestController
public class PublicKeyLookupController 
    //code removed for brevity

【讨论】:

以上是关于如何在使用纯 JavaScript 的 AJAX 调用中设置 CORS 标头,这会影响其他休​​息服务?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 JavaScript 中使用 JSONP 请求执行 Ajax 调用? [复制]

纯Javascript中的AJAX发布实现[重复]

纯JavaScript实现异步Ajax的基本原理

如何使用 Vanilla JavaScript/Ajax 获取地理位置 - 国家和城市

纯 JavaScript 的 AJAX 请求出现“ActionController::InvalidCrossOriginRequest”错误

在 JS 中如何使用 Ajax 来进行请求