gin跨域問題
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(Cors()) //開啟中間件 允許使用跨域請求
r.run()
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //請求頭部
if origin != "" {
//接收客戶端發(fā)送的origin (重要F隙摇)
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
//服務(wù)器支持的所有跨域請求的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
//允許跨域設(shè)置可以返回其他子段抱环,可以自定義字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
// 允許瀏覽器(客戶端)可以解析的頭部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
//設(shè)置緩存時間
c.Header("Access-Control-Max-Age", "172800")
//允許客戶端傳遞校驗(yàn)信息比如 cookie (重要)
c.Header("Access-Control-Allow-Credentials", "true")
}
//允許類型校驗(yàn)
if method == "OPTIONS" {
c.JSON(http.StatusOK, "ok!")
}
defer func() {
if err := recover(); err != nil {
log.Printf("Panic info is: %v", err)
}
}()
c.Next()
}
}