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?