go - 尽管选项响应中出现“Access-Control-Allow-Origin” header ,stilll却出现cors错误

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

我要求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.
我不确定这里出了什么问题。谁能帮忙。

最佳答案

当浏览器对服务器进行OPTIONS调用时,浏览器不会发送承载 token 。
这将像

curl -X OPTIONS https://mydomain/v0/currencies -i
在我的情况下返回401且未设置标题。
但是我还没有意识到这一点,因为我总是使用不记名 token 来请求curl,直到我的一位同事指出这一点。
现在,删除了对OPTIONS调用的身份验证检查及其正常工作。

关于go - 尽管选项响应中出现“Access-Control-Allow-Origin” header ,stilll却出现cors错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62898761/

相关文章:

html - 使用 Go 服务器时 MIme 类型不正确

go - 扇出,多播,接收者数量未知

nginx - 如何使用 nginx 运行 Go http 服务器

javascript - Yammer CORS 错误仅针对某些 API 调用出现

javascript - 收到错误来源 'null' 已被 CORS 策略阻止?

amazon-web-services - 经过身份验证登录后,AWS Cognito NotAuthorizedException "Invalid Access Token"错误

javascript - 无法获得映射到 Angular 2 代码中的正确 http 响应

go - 在 golang 中使用自己的类型的最佳实践。 Alians 构建类型

javascript - 跨源资源共享 (CORS) 概念

javascript - 赠送带有激活码的小部件(网络应用程序)