在go中的gin需要跨域中间件
使用Use()可以把它看中间件
在入口文件写入
func Cors() gin.HandlerFunc {
return func(context *gin.Context) {
method := context.Request.Method
context.Header("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
context.Header("Access-Control-Allow-Credentials", "true")
if method == "OPTIONS" {
context.AbortWithStatus(http.StatusNoContent)
}
context.Next()
}
}
并且在main.go入口文件
func main() {
router := gin.Default()
router.Use(Cors()) //解决跨域
gin.SetMode(gin.DebugMode) //开启dug
router.Run(":8000") //映射端口
}
重新执行再次尝试请求即可