2017-10-20 397 views
3

我試圖在Chrome新選項卡擴展中使用W3C的CSS驗證器Web服務API。 The docs聲稱的請求一個簡單的HTTP GET調用的URI,所以我想這應該工作:如何在資源不允許CORS的情況下創建「簡單」GET請求?

fetch('http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json') 
.then((response) => { 
    // do stuff with response 
}); 

不幸的是,承諾失敗,我得到一個消息,如:

Failed to load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access.

如何我應該做一個「簡單的」GET請求,如果資源不允許CORS

謝謝!

+0

_不通過客戶端JavaScript? – CBroe

+0

我得到這個錯誤:'沒有'Access-Control-Allow-Origin'標題出現在請求的資源上。原因'http://blah-blah.com'因此不被允許訪問。如果一個不透明的響應滿足您的需求,請將請求的模式設置爲'no-cors'來取消禁用CORS的資源。'如果我設置了'{mode:'no-cors'},它可以正常工作。 – Anthony

回答

2

2017年10月22日更新:change for adding CORS support to the CSS Validator被合併並推向生產,所以下面現在按原樣運行:

const validatorURL = 'https://jigsaw.w3.org/css-validator/validator' + 
 
    '?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json'; 
 
fetch(validatorURL) 
 
    .then(response => response.json()) 
 
    .then(results => console.log(results))


原來的答覆:

CSS驗證只是不發送必要的CORS響應頭。要解決這個問題,我已經有raised a pull request with a change against the CSS Validator sources這將使您的代碼片段按原樣工作。一旦變更合併並投入生產,我會在此發佈更新。

在此期間,您可以解決該問題通過使您的申請通過CORS代理:

const proxyURL = 'https://cors-anywhere.herokuapp.com/'; 
 
const validatorURL = 'http://jigsaw.w3.org/css-validator/validator' + 
 
    '?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json'; 
 
fetch(proxyURL + validatorURL) 
 
    .then(response => response.json()) 
 
    .then(results => console.log(results))

對於爲什麼工作有一個大致說明,請參閱如何使用CORS代理繞過「無訪問控制 - 允許 - 源頭」問題部分答案在No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

0

您需要register the allowed origin爲擴展名的清單:

"permissions": [ 
    "http://jigsaw.w3.org/" 
    ], 

,你可能需要set the origin mode爲取功能,以及:

fetch(
'http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json', 
    {mode: 'no-cors'}) 
.then((response) => { 
    // do stuff with response 
}); 
+0

設置'mode:'no-cors''將會阻止代碼的其餘部分訪問響應。請參閱https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input/43319482#43319482上的答案 – sideshowbarker

1

從Chrome網上商店你可以添加CORS過濾器擴展。在運行代碼之前啓用過濾器。

here您可以將篩選器添加到您的Chrome瀏覽器。

相關問題