Golang gin跨域问题怎么解决

Golang gin跨域问题怎么解决

本文小编为大家详细介绍“Golanggin跨域问题怎么解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“Golanggin跨域问题怎么解决”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

gin跨域解决方案

cors1.go

packagemiddlewaresimport("github.com/gin-gonic/gin""net/http")funcCors()gin.HandlerFunc{returnfunc(c*gin.Context){method:=c.Request.Methodorigin:=c.Request.Header.Get("Origin")iforigin!=""{c.Header("Access-Control-Allow-Origin",origin)//主要设置Access-Control-Allow-Originc.Header("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE,UPDATE")c.Header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept,Authorization")c.Header("Access-Control-Expose-Headers","Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type")c.Header("Access-Control-Allow-Credentials","false")c.Set("content-type","application/json")}ifmethod=="OPTIONS"{c.AbortWithStatus(http.StatusNoContent)}c.Next()}}

cors2.go

funcCors()gin.HandlerFunc{returncors.New(cors.Config{AllowAllOrigins:false,AllowOrigins:nil,AllowOriginFunc:func(originstring)bool{returntrue},AllowMethods:[]string{"GET","POST","PUT","PATCH","DELETE","HEAD"},AllowHeaders:[]string{"Authorization","ts","Accept","Origin","DNT","X-CustomHeader","Keep-Alive","User-Agent","X-Requested-With","If-Modified-Since","Cache-Control","Content-Type","Content-Range","Range"},AllowCredentials:true,MaxAge:10*time.Minute,})}

使用中间件

packagerouterimport("github.com/gin-gonic/gin""goproejct/controllers""goproejct/middlewares"//引入中间件goproject是项目名根据自己情况)funcInitRouter(){router:=gin.Default()router.Use(Cors())//使用中间件v1:=router.Group("v1"){v1.POST("/login",controllers.Login)v1.POST("/regist",controllers.Regist)}router.Run(":8000")}

读到这里,这篇“Golanggin跨域问题怎么解决”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注恰卡编程网行业资讯频道。

Golang gin跨域问题怎么解决

发布于 2022-04-15 22:30:33
收藏
分享
海报
0 条评论
32
上一篇:golang Gin上传文件返回前端及中间件怎么实现 下一篇:JavaScript面向对象怎么实现贪吃蛇游戏
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码