Table of Contents
Question content
Version
question
502 Bad Gateway
Home Backend Development Golang Unable to access subdomain from main domain: No 'Access-Control-Allow-Origin'

Unable to access subdomain from main domain: No 'Access-Control-Allow-Origin'

Feb 09, 2024 pm 06:30 PM

Unable to access subdomain from main domain: No Access-Control-Allow-Origin

What php editor Xiaoxin will introduce to you today is a common network development problem: the subdomain cannot be accessed from the main domain, and the "Access-Control-Allow-Origin" error occurs. . This problem is often encountered in front-end development, especially when making cross-domain requests. It often results in the request being intercepted by the browser, preventing the required data from being properly obtained. In this article, we will explain the cause and solution of this error in detail to help you solve this problem quickly and ensure the normal operation of the project.

Question content

Version

go 1.17
github.com/gin-contrib/cors v1.3.1
github.com/gin-gonic/gin v1.7.7
Copy after login

question

I am running gin rest api server in my subdomain.

The react application is placed in the main domain and uses the get method and post method to access the api server, but a cors policy error occurs access to xmlhttprequest at 'https://<subdomain>.<domain>.xxx/api/ v1/users' from origin 'https:// /<domain>.xxx' has been blocked by cors policy: Response to preflight request failed access control check: 'access- control-allow-origin" header.

In web search I found the same problem and some solutions but they don't work for my case.

Code

All these programs give the same error.

Case 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)
    }
}
Copy after login

Case 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)
    }
}

Copy after login

Case 3

access-control-allow-origin is missing from the response header. · Issue #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)
    }
}

Copy after login

Take off from the terminal

> 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 -->
Copy after login

solved

This is caused by the

aws_lb_target_group setting.

Although I only provided the acm certificate to route 53 and alb, I set the protocol https in the target group.

I replaced https with http and now it works.

Workaround

The first step in diagnosing this type of issue is to check the preflight requests directly in chrome devtools.

Comments:

    Check
  1. disable cache to prevent preflight responses from being cached.
  2. Find requests of type
  3. preflight.
The next step is to copy the preflight request as a

curl command (right-click on the request, select copy->copy as curl in the context menu ) and directly use the curl tool to test the request (remember to modify the command to add the -i option for printing response headers).

It appears that you are encountering this issue in a production environment, where the reverse proxy between the browser and your service may be blocking the

access-control-allow-origin header by default. Try sending the preflight request directly to your service and see if that makes any difference.

Update (after providing preflight response):

It turns out that this is not a cors problem at all. The request failed with status code

502 bad gateway. The application was not deployed correctly.

BTW, I've tested case 1 and it works:

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()
}
Copy after login
$ 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
Copy after login

The above is the detailed content of Unable to access subdomain from main domain: No 'Access-Control-Allow-Origin'. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles