Go 語言手搓一個簡單的跨域還是比較容易的, 但自己手搓一批通用代碼總歸還是麻煩了點.
如果使用 Gin 的話, 有現成的跨域中間件可以用. github.com/gin-contrib/cors
注意事項
現在大多前后端分離的項目中, 會在請求中使用此 hearder Authorization: Bearer xxx
,
主要添加到允許的請求頭中, 不然跨越請求還是會報錯.
代碼如下:
r := gin.Default()
// CORS
corsConf := cors.DefaultConfig()
corsConf.AddAllowHeaders("Authorization")
corsConf.AllowAllOrigins = true
r.Use(cors.New(corsConf))
// 注冊路由...