如何在资源不允许CORS的情况下创建“简单”GET请求?
我试图在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
?
谢谢!
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。
您需要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
});
设置'mode:'no-cors''将会阻止代码的其余部分访问响应。请参阅https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input/43319482#43319482上的答案 – sideshowbarker
_不通过客户端JavaScript? – CBroe
我得到这个错误:'没有'Access-Control-Allow-Origin'标题出现在请求的资源上。原因'http://blah-blah.com'因此不被允许访问。如果一个不透明的响应满足您的需求,请将请求的模式设置为'no-cors'来取消禁用CORS的资源。'如果我设置了'{mode:'no-cors'},它可以正常工作。 – Anthony