html - 使用 HTML5 获取 API 允许访问控制允许来源 header

标签 html url fetch-api

我正在使用 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/

相关文章:

javascript - JavaScript Canvas 可以像位图一样进行操作吗?它是否针对该用途进行了优化?

html - 如何像此处的图像一样创建虚线 div 边框

iphone - 在应用程序中打开 html 链接

javascript - 在 JavaScript 中将哈希 url 解析为对象?

git - 我怎样才能打破 git config <url>.insteadOf <url> 的链接

javascript - HTTP请求错误码429抓不到

html - CSS 图像宽度 100%,但仍有一些背景

html - jquery上传前如何获取文件名?

javascript - 从服务器,如何识别 javascript fetch() 调用(asp.net mvc)

javascript - react "Unhandled Rejection (TypeError): this.state.features.map is not a function"