首页 > 其他分享 >gin-解决跨域问题

gin-解决跨域问题

时间:2022-11-03 10:11:05浏览次数:45  
标签:Control 跨域 Header Access middlewares Allow 解决 gin

1.在middlewares中创建cors.go文件

package middlewares

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
	}
}

  2.使用

在route中添加Use(middlewares.Cors())


package initialize

import (
"github.com/gin-gonic/gin"
"mxshop-api/user-web/middlewares"
"mxshop-api/user-web/router"
)

func Routers() *gin.Engine {
Router := gin.Default()
Router.Use(middlewares.Cors())
ApiGroup := Router.Group("v1")
router.InitUserRoute(ApiGroup)
return Router
}


  

标签:Control,跨域,Header,Access,middlewares,Allow,解决,gin
From: https://www.cnblogs.com/wlike/p/16853507.html

相关文章