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://
上不存在“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>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