gin-gonic跨域访问

package main

import (
    "time"

    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    r.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"http://10.0.0.11:8080"},// 允许的前端地址
        AllowMethods:     []string{"PUT", "GET", "DELETE","POST"}, //允许的方法
        AllowHeaders:     []string{"Content-Type,AccessToken,X-CSRF-Token, Authorization, Token"},  //添加的header
        ExposeHeaders:    []string{"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type"},
        AllowCredentials: true,
        AllowOriginFunc: func(origin string) bool {
            return origin == "http://10.0.0.11:8080"  // 允许的前端地址
        },
        MaxAge: 12 * time.Hour,
    }))
    r.Run()
}


    

这种Default()的方式有人说可以允许所有的origin,经过测试不起作用。

func main() {
    router := gin.Default()
    // same as
    // config := cors.DefaultConfig()
    // config.AllowAllOrigins = true
    // router.Use(cors.New(config))
    router.Use(cors.Default())
    router.Run()
}

你可能感兴趣的:(gin-gonic跨域访问)