1

I receive this CORS error:

Access to fetch at 'http://127.0.0.1:5000/dashboard/1' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I set up the necessary code in my backend (using go):

func main() {
    router := gin.Default()
    router.Use(addHeaders())
    router.GET("dashboard/:id", GetDashboardById)
    router.GET("dashboardData", GetDashboardData)
}

func addHeaders() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "http://127.0.0.1:5173")
        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")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

The route "dashboardData" works fine, no CORS issues. However, route "dashboard/:id" seems to be the cause of the error. I thought it might be caused by the parameter, so I hard coded "dashboard/1" in my backend and frontend (react using redux toolkit), but the error remains. Interesting enough, "dashboard/asdf" works just fine.

What is going on here?

Zeke Lu
  • 6,349
  • 1
  • 17
  • 23
  • 1
    Does this answer your question? [Go gin framework CORS](https://stackoverflow.com/questions/29418478/go-gin-framework-cors) – Mahmudul Haque May 29 '23 at 22:29
  • 1
    I can not reproduce the issue with the current information. Please share the HTTP traffic (see [this answer](https://stackoverflow.com/questions/75935165/failed-to-access-subdomain-from-main-domain-no-access-control-allow-origin/75935458#75935458)) and the log from gin. – Zeke Lu May 30 '23 at 02:13
  • @MahmudulHaque I used this code excpet I used my exact address instead of * in allow origin, because this would cause another CORS error: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. – programmingfun May 30 '23 at 07:08
  • 1
    @ZekeLu thank you very much for the link! I didn't disable caching which seems to have caused the error (yes i feel very dumb). – programmingfun May 30 '23 at 07:10
  • @programmingfun Instead of re-implementing CORS, you should rely on a middleware that handles that concern for you and just configure it. – jub0bs May 30 '23 at 15:40

0 Answers0