我试图从惠普Alm的REST API中获取一些数据。它使用一个小的curl脚本工作得很好——我得到了我的数据。

现在用JavaScript、fetch和ES6(或多或少)来实现这一点似乎是一个更大的问题。我一直收到这个错误信息:

无法加载获取API。对飞行前请求的响应则不然 pass访问控制检查:没有' access - control - allow - origin '头 显示在所请求的资源上。“http://127.0.0.1:3000”是 因此不允许访问。响应的HTTP状态代码为501。 如果不透明响应满足您的需求,请将请求的模式设置为 'no-cors'获取禁用CORS的资源。

我明白这是因为我试图从我的本地主机内获取数据,解决方案应该使用跨起源资源共享(CORS)。我认为我确实这样做了,但不知为何,它要么忽略了我在头文件中写的内容,要么是其他问题。

那么,是否存在执行问题?我做错了吗?很遗憾,我无法查看服务器日志。我真的有点卡在这里了。

function performSignIn() {

  let headers = new Headers();

  headers.append('Content-Type', 'application/json');
  headers.append('Accept', 'application/json');

  headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
  headers.append('Access-Control-Allow-Credentials', 'true');

  headers.append('GET', 'POST', 'OPTIONS');

  headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));

  fetch(sign_in, {
      //mode: 'no-cors',
      credentials: 'include',
      method: 'POST',
      headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

我正在使用Chrome浏览器。我也尝试使用Chrome CORS插件,但随后我得到另一个错误消息:

响应中的'Access-Control-Allow-Origin'报头的值 当请求的凭据模式为时,一定不能是通配符'*' “包括”。因此,来源“http://127.0.0.1:3000”是不允许的 访问。对象发起的请求的凭据模式 XMLHttpRequest由withCredentials属性控制。


当前回答

我犯过很多次这样的错误,正因为如此,我给大家列了一张“清单”。

Enable CORS on your project: If you're using Node.js (by example) you can use: npm install cors; import cors from 'cors'; app.use(cors()); You can manually set the headers like this (if you want it): app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authortization'); res.setHeader('Acces-Control-Allow-Methods', 'GET, POST, PATCH, DELETE'); Remember to add http:// to your API link in your frontend project, some browsers like Chrome do not accept a request using CORS if the request URL isn't HTTP or HTTPS: http://localhost:3000/api Check if your project is using a proxy.config.js file. See Fixing CORS errors with Angular CLI proxy.

其他回答

对于Node.js和Express.js后端,我使用这个:)

App.use(函数(req, res, next) { res.header(“Access-Control-Allow-Origin”、“YOUR-DOMAIN.TLD”);//更新到匹配你将发出请求的域 res.header("Access-Control-Allow-Headers", "Origin, x - request - with, Content-Type, Accept"); next (); });

更多详情:CORS在ExpressJS

在2021年12月,Chrome 97,授权:持有人…不允许,除非它在Access-Control-Allow-Headers preflight响应中(忽略*)。它发出了这样的警告:

[Deprecation] authorization will not be covered by the wildcard symbol (*)

参见:Chrome企业版发布说明,Chrome 97

它似乎也对Access-Control-Allow-Origin上的*执行了相同的限制。如果您现在想在*类行为被阻止后恢复它,您可能必须读取请求者的原点,并在预飞行响应中返回它作为允许的原点。

在某些情况下,当存在其他无效的凭据(例如:过期的JWT)时,库可能会删除Access-Control-Allow-Origin响应标头。然后,浏览器显示“No 'Access-Control-Allow-Origin'头是存在的”错误,而不是实际的错误(在这个例子中可能是过期的JWT)。请确保您的库不会丢失报头,从而使客户端感到困惑。

对我来说,解决办法简直太蠢了……允许的原点不应该有斜杠。

例如:https://example.com/ -> https://example.com

这只是我的个人意见……关于如何使用CORS代理来绕过“无访问控制-允许起源标头”问题

对于那些在后端使用php的人来说,部署“CORS代理”非常简单:

创建一个名为'no-cors.php'的文件,内容如下: $URL = $_GET[' URL ']; file_get_contents ($ URL)回波json_encode (); die (); 在前端,执行如下操作: fetch('https://example.com/no-cors.php' + '?Url =' + Url) 不要犹豫(反应= >{* /处理响应/ *})”

出现问题是因为你在前端添加了以下代码作为请求头:

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

这些头属于响应,而不是请求。所以去掉它们,包括这一行:

headers.append('GET', 'POST', 'OPTIONS');

你的请求有“Content-Type: application/json”,因此触发了所谓的CORS preflight。这导致浏览器使用OPTIONS方法发送请求。详细信息请参见CORS飞行前准备。

因此,在你的后端,你必须通过返回响应头来处理这个预飞行的请求,其中包括:

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, OPTIONS
Access-Control-Allow-Headers : Origin, Content-Type, Accept

当然,实际的语法取决于后端使用的编程语言。

在你的前端,它应该像这样:

function performSignIn() {
    let headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic ' + base64.encode(username + ":" +  password));
    headers.append('Origin','http://localhost:3000');

    fetch(sign_in, {
        mode: 'cors',
        credentials: 'include',
        method: 'POST',
        headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed: ' + error.message));
}