


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.
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 2package 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) } }
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 3package 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) } }
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) } }
> 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> 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 -->
This is caused by the
aws_lb_target_group setting.
Comments:
- Check
- disable cache
to prevent preflight responses from being cached.
Find requests of type - preflight
.
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).
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 code502 bad gateway. The application was not deployed correctly.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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

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

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

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

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

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

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