2017-03-11 45 views
1

我正在嘗試使用Ajax從API請求信息。當試圖運行下面的代碼,我收到此錯誤:CORS預檢響應錯誤

XMLHttpRequest cannot load. Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.

下面的代碼:

var Onion = { 
    "async": true, 
    "crossDomain": true, 
    "url": "https://webhose.io/search?token=fc70c82d-7bd6-4bed-aafe-4d4e65c7e5db&format=json&q=&site=theonion.com&size=12", 
    "dataType": "json", 
    "method": "GET", 
    "headers": { 
    "cache-control": "no-cache", 
    "postman-token": "9a49be98-19cb-ebc6-9f52-4be90c88222b", 
    "Access-Control-Allow-Headers": true, 
    } 
} 

$.ajax(Onion).done(function (response) { 
    console.log(response); 
    console.log(response.posts[0].title); 

我是一個開始編碼器,我相信我需要的東西添加到標題。有什麼建議麼?

在此先感謝您的幫助!

+2

這意味着您嘗試訪問的網站未配置爲允許它。 – Pointy

+0

預檢請求在發送CORS有效性檢查的最終請求之前完成。 檢查答案:http://stackoverflow.com/questions/8685678/cors-how-do-preflight-an-httprequest – jsertx

回答

2

你在你的請求發送這3 HTTP頭:

"cache-control": "no-cache" 
"postman-token": "9a49be98-19cb-ebc6-9f52-4be90c88222b" 
"Access-Control-Allow-Headers": true 

瀏覽器引發此錯誤:

XMLHttpRequest cannot load https://webhose.io/search?token=fc70c82d-7bd6-4bed-aafe-4d4e65c7e5db&format=json&q=&site=theonion.com&size=12&_=1489245026633 . Request header field postman-token is not allowed by Access-Control-Allow-Headers in preflight response.

而在HTTP響應,遠程服務器發送你這個頭:

Access-Control-Allow-Headers:accept, origin, Content-type, x-json, x-prototype-version, x-requested-with, authorization 

這意味着既不緩存控制,也不郵遞員令牌,也不接入控制允許集管 HTTP標頭被允許在HTTP請求,僅接受原點內容類型的x JSONx原型版本,x請求與,授權是允許的。