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

Posted

技术标签:

【中文标题】修复不同本地主机之间的“cors”请求。 405(不允许的方法)【英文标题】:Fix 'cors' request between different localhosts. 405 (Method Not Allowed) 【发布时间】:2018-10-22 15:08:02 【问题描述】:

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

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.

P.S 服务器工作在: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.

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

【问题讨论】:

【参考方案1】:

您需要在 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 以匹配请求的标头。

【讨论】:

这里的 URL 我应该用目标服务器 url 替换它,还是用我发送请求的那个 URL 替换它? https ://domain:port

以上是关于修复不同本地主机之间的“cors”请求。 405(不允许的方法)的主要内容,如果未能解决你的问题,请参考以下文章

由于来自本地主机的 CORS 问题,请求失败

CORS 问题? - 预检响应包含无效的 HTTP 状态代码 405

CORS 预检请求返回 HTTP 405

405不允许nginx,CORS? Nginx配置?或者是其他东西?

从我的本地主机客户端发出请求而没有 cors 错误

Ngrok 在隧道我的本地主机(Laravel)时返回 405 Method Not Allowed