本文主要是介绍golang 服务端遇到strict-origin-when-cross-origin,解决跨域整理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
golang 服务端遇到strict-origin-when-cross-origin,解决跨域整理
- 代码汇总:
func Cors() gin.HandlerFunc {return func(c *gin.Context) {method := c.Request.Methodorigin := c.Request.Header.Get("Origin")fmt.Println("origin",origin)if origin != "" {//接收客户端发送的origin (重要!)c.Writer.Header().Set("Access-Control-Allow-Origin", origin)//服务器支持的所有跨域请求的方法c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")//允许跨域设置可以返回其他子段,可以自定义字段c.Header("Access-Control-Allow-Headers", "Authorization, content-type, Content-Length, X-CSRF-Token, Token,session,Access-Control-Allow-Headers,account")// 允许浏览器(客户端)可以解析的头部 (重要)c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")//设置缓存时间c.Header("Access-Control-Max-Age", "172800")//允许客户端传递校验信息比如 cookie (重要)c.Header("Access-Control-Allow-Credentials", "true")//c.Set("Content-Type", "application/json")}//允许类型校验if method == "OPTIONS" {c.JSON(http.StatusOK, "ok!")}defer func() {if err := recover(); err != nil {fmt.Printf("Panic info is: %v\n", err)}}()c.Next()}
}
这篇关于golang 服务端遇到strict-origin-when-cross-origin,解决跨域整理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!