2017-04-13 157 views
0

我的問題是,我無法發送正確的請求到服務器以json行的形式從他那裏得到答案。
這裏是我的代碼:AJAX REST API請求

$.ajax({ 
    type: "GET", 
    url: url, 
    dataType: 'json', 
    crossDomain: true, 
    username: 'username', 
    password: 'password', 
    headers: { 
     'Access-Control-Allow-Origin': '*' 
    }, 
    success: function(response) { 
     console.log(response); 
    } 
}) 

當我嘗試發送一個請求,我得到一個錯誤:

XMLHttpRequest cannot load URL. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

+0

嗨, 請參閱http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed -by-access-control-allow-origin – Rikusor

+0

首先你忘記了你的ajax調用中的數據選項。其次,如果系統出現故障,我們需要查看服務器請求應該是什麼樣的,3rd。允許起源是與我認爲與ajax結合最多的搜索失敗之一;)與千分之一谷歌結果 – mtizziani

+0

如果前端應用程序在一個不同的領域,而不是你要求的那個領域,那麼你應該與後面的人討論 - 如何將數據發送到跨域。如果是關於CORS,那麼一切都由瀏覽器處理。刪除由服務器發送的「Access-Control-Allow-Origin」標題。添加「Accept:application/json」以通知服務器數據需要序列化爲JSON。你應該保留一些時間並閱讀CORS。它將長期爲您服務。例如,請查看[LINK](http://restlet.com/company/blog/2015/12/15/understanding-and-using-cors/)。 – andreim

回答

0
var dataSet = { 
    username: 'username', 
    password: 'password', 
} 

$.ajax({ 
    type: "GET", 
    url: url, 
    dataType: 'json', 
    crossDomain: true, 
    data: dataSet, 
    // the origin header has to be set server side 
    /* 
    headers: { 
    'Access-Control-Allow-Origin': '*' 
    }, 
    */ 
    success: function(response) { 
    console.log(response); 
    } 
}); 

參數由數據集和選擇數據分配。 的允許原產頭必須設置服務器端,而不是在客戶端