我正在使用 HTML5 获取 API。
var request = new Request('https://davidwalsh.name/demo/arsenal.json');
fetch(request).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
// Yay, `j` is a JavaScript object
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
我可以使用普通的 json 但无法获取上述 api url 的数据。 它抛出错误:
Fetch API cannot load https://davidwalsh.name/demo/arsenal.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' 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.
最佳答案
正如 epascarello 所说,托管资源的服务器需要启用 CORS。您可以在客户端执行的操作(可能还有您正在考虑的操作)是将获取模式设置为 CORS(尽管我认为这是默认设置):
fetch(request, {mode: 'cors'});
然而,这仍然需要服务器也启用 CORS,并允许您的域请求资源。
查看 CORS documentation ,还有这个 awesome Udacity video解释 Same Origin Policy .
您也可以在客户端使用 no-cors 模式,但这只会给您一个不透明的响应(您无法读取正文,但响应仍然可以由 service worker 缓存或由某些 API 使用,如 <img>
):
fetch(request, {mode: 'no-cors'})
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
关于html - 使用 HTML5 获取 API 允许访问控制允许来源 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36878255/