Gin 框架跨域设置,使用axios请求
gin 跨域 使用axios 请求导致options访问
·
跨域设置可以使用官网推荐的插件
github.com/gin-contrib/cors
也可以自己写一个中间件
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
if origin != "" {
c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
c.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", "true")
}
c.Next()
}
}
当然上述的可以进行基本的请求操作。如果修改了header,使用浏览器进行 Get Post Header等请求的话,会默认进行OPTIONS的请求进行试探,要做下处理。
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
if origin != "" {
c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
c.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", "true")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
注意的是Access-Control-Allow-Headers和Access-Control-Allow-Methods 值 如果设置不当也会造成跨域问题无法进行访问,可以去掉也可以进行加 * 操作
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
if origin != "" {
c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
c.Header("Access-Control-Allow-Methods", "*")
//c.Header("Access-Control-Allow-Headers", "*")
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")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
更多推荐
已为社区贡献4条内容
所有评论(0)