I'm trying to make an API call to my endpoint (http:localhost:8080/orders?page=10&pageSize=10) written in Go with the Gin framework. My frontend is a Nextjs app. I'm getting "origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource".
I've already tried using https://github.com/gin-contrib/cors and https://github.com/rs/cors. I also tried to do it setting the headers manually but I can't seem to make it work.
Right now my code is looking like this:
func Init(init *configs.Initialization) *gin.Engine {
router := gin.New()
router.Use(cors.Default())
router.Use(gin.Logger())
router.Use(gin.Recovery())
orders := router.Group("/orders")
{
orders.GET("/", init.OrderController.GetOrders)
orders.GET("/:orderID", init.OrderController.GetOrder)
}
return router
}
With cors being imported from "github.com/gin-contrib/cors".
Any help is appreciated, I've tried every answer that I've found but no luck yet.
Some things take into account that may help you solve your issue:
CORS wont be a problem when dealing with Simple Requests
TLDR
Simple requests in Cross-Origin Resource Sharing (CORS) are requests that do not trigger preflight checks. They must meet the following criteria:
HTTP Methods: Limited to GET, HEAD, or POST.
Content-Type: The Content-Type header must be one of the following:
GETrequest without any custom/aditional headers CORS should not be a problem.Make sure the following cors options are set correctly:
Access-Control-Allow-Origin: This header indicates which origins are allowed to access the resource. It can be set to a specific origin, "*", or a list of allowed origins.
Access-Control-Allow-Methods: Specifies the methods (HTTP verbs) that are allowed when accessing the resource. For example, "GET", "POST", "PUT", etc.
Access-Control-Allow-Headers: Indicates which headers can be used during the actual request. This header is used in response to a preflight request.
Access-Control-Allow-Credentials: Specifies whether the response to the request can be exposed when the credentials flag is true. This allows for sending credentials (such as cookies or authorization headers) with the request.
Access-Control-Max-Age: Specifies how long the results of a preflight request (the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.
Access-Control-Expose-Headers: Indicates which headers can be exposed as part of the response by listing their names.
Access-Control-Request-Method: Used when issuing a preflight request to indicate the method (such as GET, POST, etc.) that will be used in the actual request.
Access-Control-Request-Headers: Used when issuing a preflight request to indicate which headers will be sent with the actual request.