代码之家  ›  专栏  ›  技术社区  ›  Filipe Teixeira

将CORS调用设置为GET而非OPTIONS

  •  0
  • Filipe Teixeira  · 技术社区  · 10 年前

    我正在创建CORS调用,如下所示:

    createCORSRequest: function(method, url) {
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
    
        if ("withCredentials" in xhr) {
            // Check if the XMLHttpRequest object has a "withCredentials" property.
            // "withCredentials" only exists on XMLHTTPRequest2 objects.
            console.log("Sending request with credneitials");
            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 {
            xhr = null;
        }
    
        xhr.setRequestHeader('Authorization', 'Bearer bf6dcfd4e975a007dc8184be6bcf580c'); //Authorization details needed
    
        return xhr;
    }
    

    问题是,这总是作为OPTIONS调用发送,服务器根本无法处理。如果我删除

    xhr.setRequestHeader('Authorization', 'Bearer bf6dcfd4e975a007dc8184be6bcf580c');
    

    那么它变成GET请求,但是如果没有访问令牌,服务器将不会处理它。

    是否有方法在GET请求中发送授权标头?

    或者我必须修改服务器以处理OPTIONS请求?一、 e.飞行前等。

    谢谢你的帮助。

    1 回复  |  直到 10 年前
        1
  •  2
  •   Quentin    10 年前

    如果您设置了Authorization标头,那么您正在进行一个复杂的请求,您必须在浏览器发出GET请求之前处理OPTIONS预检。

    如果不处理OPTIONS请求,则无法设置标头。