Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS issue when trying to access an endpoint from a React application 😱 #4021

Open
SoniSuciadi opened this issue Jul 31, 2024 · 2 comments

Comments

@SoniSuciadi
Copy link

Description

I am experiencing a CORS issue when trying to access an endpoint from a React application running at http://localhost:3000 to a Gin server running at http://localhost:6969. Even though I have added CORS middleware using gin-contrib/cors, I still get the error No 'Access-Control-Allow-Origin' header is present on the requested resource.

How to reproduce

Here is the code used in my Go application:

package main

import (
	"bank-back-office-be/config"
	"bank-back-office-be/env"
	"bank-back-office-be/server/router"
	"bank-back-office-be/server/middleware"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/gin-contrib/cors"
	_ "github.com/lib/pq"
)

func init() {
	config.LoadEnv()
	env.GetEnv()
}

func main() {
	gin.SetMode(os.Getenv("GIN_MODE"))
	port := env.Port

	app := gin.Default()

	// Add CORS middleware
	app.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{"POST", "OPTIONS", "GET", "PUT", "PATCH", "DELETE"},
		AllowHeaders:     []string{"Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	db := config.NewDB()

	// HARDCODE
	db.SetUserId("532e7219-9ce5-4002-9e03-f9308c2f87c2")

	defer db.Close()

	router.SetupRoutes(app, db)
	server := &http.Server{
		Addr:    fmt.Sprintf(":%d", port),
		Handler: app,
	}

	log.Printf("Server running on PORT %d", port)
	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatal(err)
	}
}

package middleware

import (
	"bank-back-office-be/env"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"time"
)

func getAllowOrigins() []string {
	if len(env.AllowOrigins) > 0 {
		return env.AllowOrigins
	}
	return []string{"*"}
}

func getAllowHeaders() []string {
	return []string{
		"Content-Type",
		"Content-Length",
		"Accept-Encoding",
		"Authorization",
		"accept",
		"origin",
		"Cache-Control",
		"clientpath",
	}
}

func CORSMiddleware() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowOrigins:     getAllowOrigins(),
		AllowMethods:     []string{"POST", "OPTIONS", "GET", "PUT", "PATCH", "DELETE"},
		AllowHeaders:     getAllowHeaders(),
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	})
}


Expectations
My expectation is to access the endpoint successfully without CORS errors:

$ curl http://localhost:6969/v1/help-center/faq

Actual result
However, what I get is the following error:

$ curl -i http://localhost:6969/v1/help-center/faq
HTTP/1.1 307 Temporary Redirect
Location: /v1/help-center/faq
Content-Length: 0
Date: Wed, 31 Jul 2024 12:34:56 GMT

In the React application, I get the following error in the console:

Access to XMLHttpRequest at 'http://localhost:6969/v1/help-center/faq' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST http://localhost:6969/v1/help-center/faq net::ERR_FAILED 307 (Temporary Redirect)

![Tangkapan Layar 2024-07-31 pukul 22 38 11](https://github.com/user-attachments/assets/dadf7b85-a340-47d4-a794-853c785971c9)
<img width="329" alt="Tangkapan Layar 2024-07-31 pukul 22 38 34" src="https://github.com/user-attachments/assets/3acd327e-cbb5-43df-b630-384c9d4dfeb0">
@SoniSuciadi
Copy link
Author

SoniSuciadi commented Jul 31, 2024

Tangkapan Layar 2024-07-31 pukul 22 40 42 ![Tangkapan Layar 2024-07-31 pukul 22 40 53](https://github.com/user-attachments/assets/be23a84d-7233-47ec-bc50-4ded8eb952a9)

Tangkapan Layar 2024-07-31 pukul 22 41 25
Tangkapan Layar 2024-07-31 pukul 22 41 36
Tangkapan Layar 2024-07-31 pukul 22 41 55
Tangkapan Layar 2024-07-31 pukul 22 42 03

@JimChenWYU
Copy link

Are you sure your react app running at 3000, and your gin server running at 6969 ?

$ curl -i http://localhost:6969/v1/help-center/faq
HTTP/1.1 307 Temporary Redirect
Location: /v1/help-center/faq
Content-Length: 0
Date: Wed, 31 Jul 2024 12:34:56 GMT

In the React application, I get the following error in the console:

Access to XMLHttpRequest at 'http://localhost:6969/v1/help-center/faq' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST http://localhost:6969/v1/help-center/faq net::ERR_FAILED 307 (Temporary Redirect)

![Tangkapan Layar 2024-07-31 pukul 22 38 11](https://github.com/user-attachments/assets/dadf7b85-a340-47d4-a794-853c785971c9)
<img width="329" alt="Tangkapan Layar 2024-07-31 pukul 22 38 34" src="https://github.com/user-attachments/assets/3acd327e-cbb5-43df-b630-384c9d4dfeb0">

from this log, I guss your react app is running at 6969

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants