【问题标题】:Though 'Access-Control-Allow-Origin' header present in options response , stilll getting cors error尽管选项响应中存在“Access-Control-Allow-Origin”标头,但仍然出现 cors 错误
【发布时间】:2020-08-03 14:59:02
【问题描述】:

我向
curl -v -X OPTIONS 'https://mydomain/v0/countries' --header 'Authorization: Bearer my_token'提出请求

在响应标头中我可以看到:

< HTTP/2 200 
< content-type: application/json
< content-length: 0
< date: Tue, 14 Jul 2020 15:26:10 GMT
< x-amzn-requestid: 1b2cc673-c84c-4949-bfc7-8340f50302c0
< access-control-allow-origin: *
< access-control-allow-headers: Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With
< access-control-request-headers: *
< x-amz-apigw-id: Pq029F_LDoEFsag=
< access-control-allow-methods: POST, OPTIONS, GET, PUT
< x-amzn-trace-id: Root=1-5f0dce92-3d4fb21c641373a4d3267554;Sampled=0
< access-control-allow-credentials: true
< x-cache: Miss from cloudfront
< via: 1.1 67e2031fa6e0a594e0371c2f15a6997b.cloudfront.net (CloudFront)
< x-amz-cf-pop: BLR50-C3
< x-amz-cf-id: LgRzPra6p1aAhncJDrVB937TVrbWy8igEnl4EF3jrPY1IqDbS8Z91g==

但是当我使用 chrome 的开发者控制台发出请求时:

(async function getData(url = '') {
  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer my_token'
    }
  });
  return response.json();
})('https://mydomain/v0/countries')

我可以看到以下错误:

Access to fetch at 'https://mydomain/v0/countries' from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

我不确定这里出了什么问题。谁能帮忙。

【问题讨论】:

  • 有趣,你能确认你的 jwt 是有效的并且没有过期吗?
  • No jwt 未过期。我尝试过生成一个新的 jwt 令牌。

标签: go cors aws-api-gateway go-gin


【解决方案1】:

当浏览器向服务器发出 OPTIONS 调用时,浏览器不会发送不记名令牌。

这将类似于

curl -X OPTIONS https://mydomain/v0/currencies -i

在我的情况下返回 401 而没有设置标题。 但我没有意识到这一点,因为我总是使用不记名令牌发出 curl 请求,直到我的一位同事指出这一点。

现在删除了对 OPTIONS 调用的身份验证检查,并且工作正常。

【讨论】:

  • 很高兴您找到了根本原因。
猜你喜欢
  • 2021-08-17
  • 2021-03-14
  • 2012-03-25
  • 1970-01-01
  • 2021-07-18
  • 2023-03-20
  • 2013-05-22
  • 2016-11-06
  • 2022-01-13
相关资源
最近更新 更多