首页 > 后端开发 > Golang > 正文

无法从主域访问子域:没有“Access-Control-Allow-Origin”

WBOY
发布: 2024-02-09 18:30:16
转载
929人浏览过

无法从主域访问子域:没有“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 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源.</domain></domain></subdomain> 上不存在“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 中的预检请求。

Phenaki
Phenaki

phenaki是一种从文本生成视频的模型

Phenaki 93
查看详情 Phenaki

注释

  1. 检查 disable cache 以防预检响应被缓存。
  2. 查找类型为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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号