gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
79.18k stars 8.03k forks source link

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

Open SoniSuciadi opened 3 months ago

SoniSuciadi commented 3 months ago

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 commented 3 months ago
Tangkapan Layar 2024-07-31 pukul 22 40 42

Tangkapan Layar 2024-07-31 pukul 22 40 53

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 commented 3 months ago

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