javascript XMLHttpRequest 无法加载 URL。请求的资源上不存在“Access-Control-Allow-Origin”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24818246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:23:10  来源:igfitidea点击:

XMLHttpRequest cannot load URL. No 'Access-Control-Allow-Origin' header is present on the requested resource

javascriptajaxcors

提问by Nikhil

Here is what I have done and understood so far:

这是我到目前为止所做和理解的:

My Webpage run from http://localhost:80, I need to access some API calls at http://localhost:8080.

我的网页从 运行http://localhost:80,我需要在 访问一些 API 调用http://localhost:8080

I require to enable CORS, as its a POST and Content-Type is application/json.

我需要启用 CORS,因为它的 POST 和 Content-Type 是 application/json。

So I implemented OPTIONS method on the server and set all the required headers.

所以我在服务器上实现了 OPTIONS 方法并设置了所有必需的标头。

Here is the OPTIONS request which the browser makes Request :

这是浏览器发出 Request 的 OPTIONS 请求:

OPTIONS /0/VERIFICATION HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML,     like Gecko) Chrome/36.0.1985.125 Safari/537.36
Access-Control-Request-Headers: x-key, x-signature, content-type
Accept: */*
Referer: http://localhost/jquery.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

Response :

回复 :

HTTP/1.1 200 OK
Allow: POST,GET,PUT,DELETE,OPTIONS
Access-Control-Allow-Origin: *
Accept: */*
Access-Control-Request-Headers: X-Key,X-Signature,Content-Type
Access-Control-Allow-Headers: X-Key,X-Signature,Content-Type
Content-Type: application/json; charset=UTF-8
Content-Length: 0

So I can see all the appropriate headers being set and all looks good until the actual request is made which fails with the following error

所以我可以看到所有适当的标头都被设置并且看起来都很好,直到发出实际请求,该请求失败并出现以下错误

Error in Chrome Console

Chrome 控制台中的错误

XMLHttpRequest cannot load http://localhost:8080/0/VERIFICATION. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

Here is my javascript code which is making the actual request

这是我的 javascript 代码,它正在发出实际请求

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
 }

function makeCorsRequest() {
    var url = "http://localhost:8080/0/VERIFICATION";
    var xhr = createCORSRequest('POST', url);
    xhr.onload = function() {
        var text = xhr.responseText;
        alert('Response from CORS request to ' + url + ': ' + title);
    };

    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    };
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("X-Signature", "abcd");
    xhr.setRequestHeader("X-Key", "key1");
    xhr.send("{json data}");
 }

I am using Chrome browser to test the above scenario, my server is a netty based server and html pages are being served via apache.

我正在使用 Chrome 浏览器来测试上述场景,我的服务器是基于 netty 的服务器,并且 html 页面是通过 apache 提供的。

Update added .htaccess based on the comment below and still the same error.

根据下面的评论更新添加的 .htaccess 并且仍然是相同的错误。

curl -v 'http://localhost/jquery.html'
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /jquery.html HTTP/1.1
> User-Agent: curl/7.36.0
> Host: localhost
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Fri, 18 Jul 2014 07:03:22 GMT
* Server Apache/2.4.9 (Unix) PHP/5.5.9 is not blacklisted
< Server: Apache/2.4.9 (Unix) PHP/5.5.9
< Last-Modified: Sun, 30 Mar 2014 06:31:53 GMT
< ETag: "3af-4f5cd17308840"
< Accept-Ranges: bytes
< Content-Length: 943
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Headers: origin, x-requested-with, x-http-method-override, content-    type
< Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
< Content-Type: text/html

回答by jgillich

You need to set the headers when you serve the html pages, too. .htaccessfor Apache:

当您提供 html 页面时,您也需要设置标题。.htaccess对于阿帕奇:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, x-http-method-override, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

回答by Nikhil

None of the browser, curl or wireshark could tell what was going wrong. The problem was very was lame, I did the following on the server :

浏览器、curl 或wireshark 都无法判断出了什么问题。问题很糟糕,我在服务器上做了以下事情:

response.addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, "X-Key,X-Signature,Content-Type");

The correctway is :

正确的方法是:

response.addHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_HEADERS, "X-Key");
response.addHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_HEADERS, "X-Signature");
response.addHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_HEADERS, "Content-Type");