'Cross-Origin Request Blocked while working with go [duplicate]

I am working with JavaScript frontend and go backend. I created an API using go gin framework.

My main.go is :

func main() {

  router := gin.Default()
  router.GET("/", getBasicBlogInfo)

  router.Use(cors.Default())
  err := router.Run("localhost:8080")
  if err != nil {
    log.Fatalln("Unable to run the server.")
  }

}

Now in my index.js

fetch('localhost:8080')
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
    console.error('Error:', error);
});

However I am getting a CORS-origin Request block error.

The error I got is :

Error: TypeError: NetworkError when attempting to fetch resource.

and the CORS one is:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.



Solution 1:[1]

import "github.com/gin-contrib/cors"

// r.Use(AllowAll())
func AllowAll() gin.HandlerFunc{
    cfg := cors.Config{
        AllowMethods:     []string{"*"},
        AllowHeaders:     []string{"*"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
    }

    cfg.AllowAllOrigins = true
    return cors.New(cfg)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thy