golang gin跨域问题怎么解决-亚博电竞手机版

golang gin跨域问题怎么解决

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

gin跨域亚博vip888的解决方案

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

展开全文
内容来源于互联网和用户投稿,文章中一旦含有亚博电竞手机版的联系方式务必识别真假,本站仅做信息展示不承担任何相关责任,如有侵权或涉及法律问题请联系亚博电竞手机版删除

最新文章

网站地图