How to solve the cors problem by developing API with gin?

using Go framework gin to develop backend API, local port is:

http://localhost:8080

basic code is:

import (
        "github.com/gin-gonic/gin"
        "github.com/rs/cors"
        // ...
)

type Post struct {
    ID uint `json:"id"`
    Title string `json:"title"`
    Body string `json:"body"`
}

func main() {
        r := gin.Default()
        
        r.Use(cors.New(cors.Config{
            AllowOrigins:  []string{"*"},
            AllowMethods:  []string{"PUT", "PATCH", "GET", "POST", "DELETE"},
            AllowHeaders:  []string{"content-type"},
            ExposeHeaders: []string{"X-Total-Count"},
        }))
        
        r.GET("/posts", GetPosts)
        r.GET("/posts/:id", GetPost)
        r.POST("/posts", CreatePost)
        r.PUT("/posts/:id", UpdatePost)
        r.DELETE("/posts/:id", DeletePost)
    
        r.Run()
}

the front end uses react-admin to access that API, local port:

http://localhost:3000

basic code is:

package main

import React from "react";
import { Admin, Resource } from "react-admin";
import jsonServerProvider from "ra-data-json-server";
import { PostList } from "./posts";

const dataProvider = jsonServerProvider("http://localhost:8080");

const App = () => (
  <Admin dataProvider={dataProvider}>
    <Resource name="posts" list={PostList} />
  </Admin>
);

export default App;

when you access http://localhost:3000/-sharp/posts in a Chrome browser, you see the following information from the browser console:

Failed to load http://localhost:8080/posts?_end=10&_order=DESC&_sort=id&_start=0: Response to preflight request doesn"t pass access control check: No "Access-Control-Allow-Origin" header is present on the requested resource. Origin "http://localhost:3000" is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request"s mode to "no-cors" to fetch the resource with CORS disabled.
index.js:2178 Warning: Missing translation for key: "Failed to fetch"
Mar.20,2021

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



gin.Use(cors.New(cors.Config{
        AllowOriginFunc:  func(origin string) bool { return true },
        AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "PATCH"},
        AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type"},
        AllowCredentials: true,
        MaxAge:           12 * time.Hour,
}))

that's fine

Menu