【问题标题】:How to make a "simple" GET request if the resource doesn't allow CORS?如果资源不允许 CORS,如何发出“简单”的 GET 请求?
【发布时间】:2018-04-02 00:15:36
【问题描述】:

我正在尝试在 Chrome 新标签扩展中使用 W3C 的 CSS Validator Web Service 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”标头 请求的资源。因此不允许 Origin 访问。

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

谢谢!

【问题讨论】:

  • 通过客户端JavaScript?
  • 我得到这个错误:No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://blah-blah.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 如果我设置{mode: 'no-cors'} 它工作正常。

标签: css cors w3c w3c-validation fetch-api


【解决方案1】:

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,这将使您的代码 sn-p 能够按原样工作。合并更改并推送到生产环境后,我将在此处发布更新。

与此同时,您可以通过 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 标头”问题部分No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API.

【讨论】:

    【解决方案2】:

    您需要 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
    });
    

    【讨论】:

    【解决方案3】:

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

    来自here,您可以将过滤器添加到您的 chrome 浏览器。

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2015-03-09
      • 2014-12-20
      • 2020-12-29
      • 2016-07-04
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多