so i have a project that use both nextjs and golang as its frontend and backend. I keep getting blocked from fetching my data because of CORS

Image

this is my cors code on the backend : ```package middleware

import ( "net/http"

"github.com/gin-gonic/gin"

)

func CORSMiddleware() gin.HandlerFunc { return func(c *gin.Context) {

    c.Header("Access-Control-Allow-Origin", "http://localhost:5051")
    c.Header("Access-Control-Allow-Credentials", "true")
    c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Header("Access-Control-Allow-Methods", "POST, HEAD, PATCH, OPTIONS, GET, PUT, DELETE")

    if c.Request.Method == http.MethodOptions {
        c.AbortWithStatus(204)
        return
    }

    c.Next()
}

}


i already specify the origin to my localhost domain but it wont work and i also have experimented in my frontend code to put no-cors but still no result. Please help me out

**Comment From: zeek0x**

Without a complete and minimal reproducible code example provided, it’s difficult to identify the exact cause of the issue. However, unless there’s a specific reason not to, I recommend using [gin-contrib/cors](https://github.com/gin-contrib/cors).

**Comment From: maruki00**

try this code

func CORSMiddleware() gin.HandlerFunc { return func(ctx *gin.Context) { if ctx.Request.Method == http.MethodOptions || ctx.Request.Header.Get("Access-Control-Request-Method") == "" { ctx.Header("Access-Control-Allow-Origin", "http://127.0.0.1:5051") // Allow requests from specific origin ctx.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") // Allowed HTTP methods ctx.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization") // Allowed headers ctx.Header("Access-Control-Allow-Credentials", "true") // Allow credentials (cookies, Authorization header) ctx.Status(200) return } ctx.Next() } }


**Comment From: DenisKantic**

This is example from my cors middleware. I'm using vuejs for frontend. Maybe you could try this.

```go
cors_config := cors.Config{
    AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
    AllowCredentials: true,
    AllowOrigins:     []string{"http://localhost:3000"},
}

r := gin.Default()
r.Use(cors.New(cors_config))

For the frontend part, I'm using axios so don't forget to include "withCredentials: true".

Also don't forget to install cors package go get github.com/gin-contrib/cors