func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //请求头部
if origin != "" {
// 当Access-Control-Allow-Credentials为true时
c.Header("Access-Control-Allow-Origin", "http://【自己的域名/ip,不要加端口号】")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-Extra-Header, 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", "true")
c.Header("Access-Control-Max-Age", "86400") // 可选
c.Set("content-type", "application/json") // 可选
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
func main() {
r := gin.Default()
r.Use(Cors()) //开启中间件 允许使用跨域请求
// 其他路由设置
r.run()
}
来源链接:https://juejin.cn/post/7028523881015017509
本文介绍了一个基于Gin框架的跨域请求处理方法,通过自定义中间件实现对HTTP请求头的修改来支持跨域访问。适用于需要解决前端与后端跨域问题的开发者。
1602

被折叠的 条评论
为什么被折叠?



