无法从主域访问子域:没有'Access-Control-Allow-Origin”
php小编小新今天为大家介绍的是一个常见的网络开发问题:无法从主域访问子域,出现了“Access-Control-Allow-Origin”错误。这个问题在前端开发中经常遇到,尤其在跨域请求时较为常见。它通常会导致请求被浏览器拦截,从而无法正常获取所需的数据。在本文中,我们将详细解释这个错误的原因和解决方法,帮助大家快速解决这个问题,保证项目的正常运行。
问题内容
版本
go 1.17 github.com/gin-contrib/cors v1.3.1 github.com/gin-gonic/gin v1.7.7
问题
我在我的子域中运行 gin rest api 服务器。
react应用程序放置在主域中,使用get方法和post方法访问api服务器,但出现cors策略错误 access to xmlhttprequest at 'https://<subdomain>.<domain>.xxx/api/v1/users' from origin 'https:// /<domain>.xxx' 已被 cors 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源.
上不存在“access-control-allow-origin”标头。
在网络搜索中,我发现了同样的问题和一些解决方案,但它们对我的情况不起作用。
代码
所有这些程序都出现相同的错误。
案例1
package gateway import ( "log" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func runserver() { r := gin.default() r.use(cors.default()) api := r.group("/api") v1 := api.group("/v1") userrouters(v1) err := r.run() if err != nil { log.printf("failed to run gateway: %v", err) } }
案例2
package gateway import ( "log" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func runserver() { r := gin.default() r.use(cors.new(cors.config{ alloworigins: []string{"*"}, allowmethods: []string{"get", "post", "put", "delete"}, allowheaders: []string{"content-type"}, allowcredentials: false, maxage: 12 * time.hour, })) api := r.group("/api") v1 := api.group("/v1") userrouters(v1) err := r.run() if err != nil { log.printf("failed to run gateway: %v", err) } }
案例3
响应标头中缺少 access-control-allow-origin。 · 问题 #29 · gin-contrib/cors
package gateway import ( "log" "github.com/gin-gonic/gin" ) func cors() gin.handlerfunc { return func(c *gin.context) { c.writer.header().set("access-control-allow-origin", "*") c.writer.header().set("access-control-allow-credentials", "true") c.writer.header().set("access-control-allow-headers", "content-type, content-length, accept-encoding, x-csrf-token, authorization, accept, origin, cache-control, x-requested-with") c.writer.header().set("access-control-allow-methods", "post, options, get, put, delete") if c.request.method == "options" { c.abortwithstatus(204) return } c.next() } } func runserver() { r := gin.default() r.use(cors()) api := r.group("/api") v1 := api.group("/v1") userrouters(v1) err := r.run() if err != nil { log.printf("failed to run gateway: %v", err) } }
从航站楼起飞
> curl 'https://alb.skhole.club/api/v1/authz' \ -X 'OPTIONS' \ -H 'authority: alb.skhole.club' \ -H 'accept: */*' \ -H 'accept-language: ja,en-US;q=0.9,en;q=0.8' \ -H 'access-control-request-headers: content-type' \ -H 'access-control-request-method: POST' \ -H 'cache-control: no-cache' \ -H 'origin: https://skhole.club' \ -H 'pragma: no-cache' \ -H 'referer: https://skhole.club/' \ -H 'sec-fetch-dest: empty' \ -H 'sec-fetch-mode: cors' \ -H 'sec-fetch-site: same-site' \ -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36' \ --compressed -i HTTP/2 502 server: awselb/2.0 date: Wed, 05 Apr 2023 04:04:13 GMT content-type: text/html content-length: 524 <html> <head><title>502 Bad Gateway</title></head> <body> <center><h1 id="Bad-Gateway">502 Bad Gateway</h1></center> </body> </html> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page --> <!-- a padding to disable MSIE and Chrome friendly error page -->
已解决
这是由 aws_lb_target_group
设置引起的。
尽管我仅向 route 53 和 alb 提供了 acm 证书,但我在目标组中设置了协议 https。
我用 http 替换了 https,现在它可以工作了。
解决方法
诊断此类问题的第一步是直接检查 chrome devtools 中的预检请求。
注释:
- 检查
disable cache
以防预检响应被缓存。 - 查找类型为
preflight
的请求。
下一步是将预检请求复制为 curl
命令(右键单击请求,在上下文菜单中选择 copy
->copy as curl)并直接使用 curl
工具测试请求(记得修改命令添加-i
选项用于打印响应标头)。
您似乎在生产环境中遇到了该问题,浏览器和您的服务之间的反向代理可能默认阻止 access-control-allow-origin
标头。尝试将预检请求直接发送到您的服务,看看是否有任何不同。
更新(提供预检响应后):
事实证明,这根本不是 cors 问题。请求失败,状态代码 502 bad gateway
。应用程序未正确部署。
顺便说一句,我已经测试了案例 1 并且它有效:
package main import ( "log" "net/http/httputil" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { r := gin.default() r.use(cors.default()) api := r.group("/api") v1 := api.group("/v1") v1.post("users", func(ctx *gin.context) { buf, err := httputil.dumprequest(ctx.request, true) if err != nil { log.printf("failed to dump request: %v", err) return } log.printf("%s", buf) }) err := r.run() if err != nil { log.printf("failed to run gateway: %v", err) } r.run() }
$ curl 'http://localhost:8080/api/v1/users' \ -X 'OPTIONS' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6' \ -H 'Access-Control-Request-Headers: content-type' \ -H 'Access-Control-Request-Method: POST' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Origin: http://127.0.0.1:5501' \ -H 'Pragma: no-cache' \ -H 'Referer: http://127.0.0.1:5501/' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: cross-site' \ -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36' \ --compressed -i HTTP/1.1 204 No Content Access-Control-Allow-Headers: Origin,Content-Length,Content-Type Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS Access-Control-Allow-Origin: * Access-Control-Max-Age: 43200 Date: Wed, 05 Apr 2023 03:50:06 GMT
以上是无法从主域访问子域:没有'Access-Control-Allow-Origin”的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

OpenSSL,作为广泛应用于安全通信的开源库,提供了加密算法、密钥和证书管理等功能。然而,其历史版本中存在一些已知安全漏洞,其中一些危害极大。本文将重点介绍Debian系统中OpenSSL的常见漏洞及应对措施。DebianOpenSSL已知漏洞:OpenSSL曾出现过多个严重漏洞,例如:心脏出血漏洞(CVE-2014-0160):该漏洞影响OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻击者可利用此漏洞未经授权读取服务器上的敏感信息,包括加密密钥等。

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

后端学习路径:从前端转型到后端的探索之旅作为一名从前端开发转型的后端初学者,你已经有了nodejs的基础,...

Go语言中字符串打印的区别:使用Println与string()函数的效果差异在Go...

本文介绍在Debian系统下监控PostgreSQL数据库的多种方法和工具,助您全面掌握数据库性能监控。一、利用PostgreSQL内置监控视图PostgreSQL自身提供多个视图用于监控数据库活动:pg_stat_activity:实时展现数据库活动,包括连接、查询和事务等信息。pg_stat_replication:监控复制状态,尤其适用于流复制集群。pg_stat_database:提供数据库统计信息,例如数据库大小、事务提交/回滚次数等关键指标。二、借助日志分析工具pgBadg

Go语言中使用RedisStream实现消息队列时类型转换问题在使用Go语言与Redis...

在BeegoORM框架下,如何指定模型关联的数据库?许多Beego项目需要同时操作多个数据库。当使用Beego...
