Gin处理跨域问题
使用gin中间件,解决跨域问题
创建一个中间件 /middleware/CORESMiddleware.go
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
func CORSMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*") //允许所有IP访问
ctx.Writer.Header().Set("Access-Control-Max-Age", "86400")
ctx.Writer.Header().Set("Access-Control-Allow-Headers", "*")
ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if ctx.Request.Method == http.MethodOptions {
ctx.AbortWithStatus(200)
} else {
ctx.Next()
}
}
}
把中间件添加到路由中去,重启程序
r.Use(middleware.CORSMiddleware(),****)