繁体   English   中英

修复不同本地主机之间的“ cors”请求。 405(不允许使用方法)

[英]Fix 'cors' request between different localhosts. 405 (Method Not Allowed)

我使用以下代码来请求文件:

function getData(imageEndpoint) {
  return fetch(imageEndpoint, {
    mode: 'cors'
  })
    .then(response => {
      console.log(response);
    })
    .then(data => {
      if (!('caches' in window)) {
        return caches.open(cacheName)
        .then(cache => {
          return cache.put(imageEndpoint, data);
        });
      }
      return data;
    })
    .catch(e => {
      console.log('Request issue, ', e);
    });
}

在以下错误消息中输出:

Failed to load http://localhost:7000/image.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' 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.

PS服务器工作:8000

当我添加cors标头时

  return fetch(imageEndpoint, {
    mode: 'cors',
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  })

引发以下错误:

http://localhost:7000/image.jpg 405 (Method Not Allowed)

index.html:1 Failed to load http://localhost:7000/image.jpg: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

您能否建议如何设置请求才能成功接收文件?

您必须在OPTIONS响应和POST响应上都具有标头Access-Control-Allow-Origin: URL Here或Access-Control-Allow-Origin:*。 您还应该在POST响应中包含标头Access-Control-Allow-Credentials:true。

您的OPTIONS响应还应该包含标头Access-Control-Allow-Headers:origin,content-type,accept以匹配请求的标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM