最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

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

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

Here is the OPTIONS request which the browser makes Request :

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

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

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.

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

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

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.

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

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

Here is the OPTIONS request which the browser makes Request :

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

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

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.

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

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
Share Improve this question edited Jul 18, 2014 at 7:05 Nikhil asked Jul 18, 2014 at 6:07 NikhilNikhil 311 gold badge1 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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

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"

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 :

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

The correct way 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");
发布评论

评论列表(0)

  1. 暂无评论