Board logo

標題: No 'Access-Control-Allow-Origin' header is present [打印本頁]

作者: lolmuta    時間: 2015-4-27 17:40     標題: No 'Access-Control-Allow-Origin' header is present

本帖最後由 lolmuta 於 2015-4-27 17:42 編輯

寫一個xmlhttp請求,但是一直出現錯誤, No 'Access-Control-Allow-Origin' header is present

[執行環境]:chrome 版本 42.0.2311.90 m

[目標]:作一個按鈕,點擊後,會產生一個xmlhttp請求,url是本網站的首頁(http://jsgears.com), 當得到正確的回應時,就將整個document改寫成
xmlhttp的responseText.


[錯誤與網頁資訊]:一開始出現這個錯誤時,以為加上header Access-Control-Allow-Origin:*就好了…但是仍然錯誤…其實,是因為查到太多看都看不懂的東西,只是取其中的關鍵來用= =,這裡想順便請教一下,是否有好的書可推薦的…

[代碼]:
<!DOCTYPE html>
<html>
<script>
function aaaa(){        
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","http://jsgears.com",true);
        xmlhttp.setRequestHeader("Access-Control-Allow-Origin","*");        
        xmlhttp.send();        
        xmlhttp.onreadystatechange=function(){
                 if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                    //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                    var responsetxt=xmlhttp.responseText;
                    document.write(responsetxt);                    
                  }
        }
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<title>Insert title here</title>
<button type="button" onclick="aaaa()">Test</button>
</head>
<body>

</body>
</html>
[詳細錯誤]:
XMLHttpRequest cannot load http://jsgears.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
作者: wmh    時間: 2015-4-28 22:38

JavaScript 基本上不允許跨網域的 request,比如說你的網頁用 localhost,就無法 request jsgears.com 的內容。
除非 server 有允許這樣做,你查到的 header 資訊是 server 要回應的,所以在 client 端加是無效的。

跨網域的 request 有很多解法,得看你實際的用途,才能知道比較正確的處理方式,
通常在自己網站上開發,都是相同 domain,因此無此問題。
若是要抓其他網站的資訊,通常是第三方網站提供 JSONP 的 API 讓你使用,
再不然就得透過自己的 server 端來處理,而非直接用 JavaScript。
作者: lolmuta    時間: 2015-4-30 08:25

回復 2# wmh


    我想要寫chrome的插件 。
我曾看過的插件,有比價功能,比如找筆電,就秀出各大網站的同類型產品,找工作的有比較其它如104 ,1111有什麼同類型的工作。
作者: wmh    時間: 2015-5-1 06:44

比價不是單純 JavaScript 做的,資料都是先在自己的 server 收集處理過,
所以 server side 可提供 JSONP 的 API 讓 JavaScript 抓資料。
作者: lolmuta    時間: 2015-5-25 17:37

本帖最後由 lolmuta 於 2015-5-25 17:40 編輯

因為我是新手,對於這種封鎖實在難以理解…
可以提供個具體的例子來說明嗎?

如果不封鎖的話呢?會發生什麼事情呢?
那用sever 端去撈資料就比較安全嗎?


查到一個可以將安全性取消的google extension
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
雖然不知道是怎麼弄的,不過看起來應該可以強制取消封鎖…




歡迎光臨 jsGears.com 技術論壇 - AJAX, JavaScript, jQuery, 網站開發, 前端效能優化 (http://jsgears.com/)