這裏是我做了什麼,至今明白:從http://localhost:80
XMLHttpRequest無法加載URL。沒有「訪問控制允許來源」標頭出現在所請求的資源
我的網頁上運行,我需要在http://localhost:8080
訪問某些API調用。
我需要啓用CORS,因爲它的POST和Content-Type是application/json。
所以我在服務器上實現了OPTIONS方法並設置了所有必需的頭文件。
這裏是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
響應:
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
所以我可以看到被設置所有適當的標題和一切看起來不錯,直到實際要求製作失敗,出現以下錯誤
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.
這是我這使得實際要求
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}");
}
我使用的Chrome瀏覽器測試上面的場景中的JavaScript代碼,我的服務器是一個基於網狀服務器和HTML頁面正在通過Apache服務。
更新根據下面的評論添加.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