Home  >  Article  >  Backend Development  >  Unable to access subdomain from main domain: No 'Access-Control-Allow-Origin'

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

WBOY
WBOYforward
2024-02-09 18:30:16738browse

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

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. </domain></domain></subdomain>

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

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

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

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>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 -->

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

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:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete