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

i keep getting cors problem #157

Open
Dancingaroundthelies opened this issue Jan 22, 2025 · 1 comment
Open

i keep getting cors problem #157

Dancingaroundthelies opened this issue Jan 22, 2025 · 1 comment

Comments

@Dancingaroundthelies
Copy link

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 :


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

@LuizWeitz
Copy link

Hi @Dancingaroundthelies , so I was having the same problem, after a few cups of coffee and some lost threads, I found the solution, if you have more than one middleware in your application, after your function r := gin.New() or r := gin.Default() you need to register the cors middleware first of all, this worked for me, if I register it after some middleware, the cors doesn't work, for example

Image

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

No branches or pull requests

2 participants