我正在尝试从HP Alm的REST API中获取一些数据.它适用于小卷曲脚本 - 我得到了我的数据.
现在使用JavaScript,fetch和ES6(或多或少)似乎是一个更大的问题.我一直收到此错误消息:
无法加载Fetch API.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许来源" http://127.0.0.1:3000 "访问.响应具有HTTP状态代码501.如果不透明响应满足您的需要,请将请求的模式设置为"no-cors"以获取禁用CORS的资源.
我知道这是因为我试图从我的localhost中获取该数据,解决方案应该使用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));
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Chrome.我也尝试使用Chrome CORS插件,但后来我收到另一条错误消息:
当请求的凭据模式为"include"时,响应中"Access-Control-Allow-Origin"标头的值不能是通配符"*".因此,不允许来源" http://127.0.0.1:3000 "访问.XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制.
我一直在我的网站上运行新闻 api,并通过将文件拖到网络浏览器中来在我的计算机上进行测试,网址会像这样显示file:///C:。然后我会将所有更改上传到我的 GitHub 存储库并在 Github 页面上运行它https://name.github.io/repository/。
很长一段时间一切都工作正常,但最终 API 停止工作并在控制台中显示错误Access to fetch at 'https://newsapi.org/v2/everything?xx' from origin 'https://name.github.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 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'到提取中,但它不起作用return response.json();
我的函数如下所示:
const url = 'https://newsapi.org/v2/everything?' +
'qInTitle=""&' +
`from=` +
'language=en&' +
'apiKey=';
const req = new Request(url); …Run Code Online (Sandbox Code Playgroud)