代码之家  ›  专栏  ›  技术社区  ›  Jeff B

如果资源不允许CORS,如何发出“简单”GET请求?

  •  3
  • Jeff B  · 技术社区  · 8 年前

    我正在尝试在Chrome的新标签扩展中使用W3C的CSS验证程序Web服务API。 The docs 声称请求是 对URI的简单HTTP 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
    });
    

    未能加载。上不存在“Access Control Allow Origin”标头 请求的资源。因此,不允许访问原点。

    我该怎么做一个“简单的” GET CORS ?

    谢谢

    3 回复  |  直到 8 年前
        1
  •  3
  •   sideshowbarker    4 年前

    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))

    有关其工作原理的详细信息,请参阅 答案部分位于 No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API .

        2
  •  0
  •   Anthony    8 年前

    你需要 register the allowed origin 对于扩展的清单:

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

    你可能需要 set the origin mode 对于fetch函数:

    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
    });
    
        3
  •  0
  •   unknown123    8 年前

    从chrome网络商店,你可以添加CORS过滤器扩展。只需在运行代码之前启用过滤器。

    从…起 here 您可以将过滤器添加到您的chrome浏览器中。