[英]Access-Control-Allow-Origin - localhost
我通過ajax接收json有問題,錯誤如下。 根據我迄今為止發現的關於錯誤的信息,這似乎是某種跨域問題,但我不知道這意味着什么以及如何解決它。
響應標頭可能存在問題(我自己創建了API並且之前沒有經驗),但是如果直接在瀏覽器中訪問URL,則會收到200 OK。
如果直接在瀏覽器中訪問url,則會顯示有效的json,因此不應該出現問題。
怎么解決這個問題?
注意:url會轉到Apache服務器,而不是我已經閱讀過有關該問題的Stack上95%問題的文件。
XMLHttpRequest cannot load http://localhost/api/v1/products?_=1355583847077.
Origin null is not allowed by Access-Control-Allow-Origin.
Error: error
$.ajaxSetup ({
url: "http://localhost/api/v1/products", // <--- returns valid json if accessed in the browser
type: "GET",
dataType: "json",
cache: false,
contentType: "application/json"
})
$.ajax({
success: function(data){
console.log("You made it!");
},
error: function(xhr) {
console.log("Error: " + xhr.statusText);
}
}).done(function(data){
console.log(data);
})
_ 1355583610778
響應標題:
Connection Keep-Alive
Content-Length 3887
Content-Type application/json
Date Sat, 15 Dec 2012 14:50:53 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By PHP/5.3.1
請求標題:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language sv-SE,sv;q=0.8,en-US;q=0.5,en;q=0.3
Connection keep-alive
Host localhost
Origin null
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0
這里沒有什么...
是的,這絕對是一個跨域問題。 但不要擔心,這個問題有兩個解決方案。
您可以在服務器上實現對JSONP(帶填充的JSON)的支持(即Fergus Morrow的解決方案 )。 JSONP開箱即用的跨域工作,基本上是JSON填充函數調用。
在.ajaxSetup
中將dataType
設置為jsonp
,然后在服務器端,您應該確保在請求中檢查名為callback
的url參數。 如果設置了該參數,則必須相應地填充JSON響應。
parseThis({ "json": "can", "be": "put", "in": "here" });
以上假設callback
設置為parseThis
。 jQuery將每默認生成的函數名,但你可以通過設置的值覆蓋此jsonpCallback
在.ajaxSetup
。
您還可以使用快捷方式通過添加?callback=?
告訴jQuery您正在請求JSONP ?callback=?
到請求網址。
另一種解決方案是在響應中設置Access-Control-Allow-Origin
標頭。
Access-Control-Allow-Origin: *
以上將允許任何資源使用跨域服務。 閱讀下面鏈接的文章,了解有關如何配置Access-Control-Allow
更多信息。
我通過在服務器代碼(php)中添加以下標題,以一種非常簡單的方式解決了這個問題:
header('Access-Control-Allow-Origin: *');
嘗試並實現某種形式的JSONP機制。 如果您正在使用PHP,它可能就像這樣簡單......
/* If a callback has been supplied then prepare to parse the callback
** function call back to browser along with JSON. */
$jsonp = false;
if ( isset( $_GET[ 'callback' ] ) ) {
$_GET[ 'callback' ] = strip_tags( $_GET[ 'callback' ] );
$jsonp = true;
$pre = $_GET[ 'callback' ] . '(';
$post = ');';
} //isset( $_GET[ 'callback' ] )
/* Encode JSON, and if jsonp is true, then ouput with the callback
** function; if not - just output JSON. */
$json = json_encode( /* data here */ );
print( ( $jsonp ) ? $pre . $json . $post : $json );
所有這一切都是檢查$_GET
var調用回調 ,然后將輸出包裝在函數調用中 - 將$_GET['callback']
名稱作為函數名稱。
那么你的AJAX調用會變成這樣的......
$.ajax({
type: 'GET',
url: '/* script here */ ',
data: /* data here - if any */,
contentType: "jsonp", // Pay attention to the dataType/contentType
dataType: 'jsonp', // Pay attention to the dataType/contentType
success: function (json) {
/* call back */
}
});
當jQuery被賦予'jsonp'
作為dataType / contentType時,它將負責為你提供一個回調函數名稱 - 並設置回調函數等; 意思是你真的不需要做任何事情!
從jQuery文檔:
“jsonp”:使用JSONP加載JSON塊。 添加額外的“?callback =?” 到URL的末尾以指定回調。 通過將查詢字符串參數“_ = [TIMESTAMP]”附加到URL來禁用緩存,除非緩存選項設置為true。
結束; JSONP將是你最好的選擇 - 我已經包含了PHP代碼,因為你的服務器端腳本正在使用PHP; 如果沒有那么原則是相同的。 不管服務器端技術如何,jQuery /客戶端的東西都保持不變。 ( 一般情況下 )
祝好運 :)
如果它是ASP.NET WEB應用程序,那么您也可以將它放在Global.aspx中:
HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Origin”,“*”);
更多PHP標頭設置
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.