作者 yangfu

跨域设置

@@ -2,6 +2,7 @@ package beego @@ -2,6 +2,7 @@ package beego
2 2
3 import ( 3 import (
4 "encoding/json" 4 "encoding/json"
  5 + "net/http"
5 "os" 6 "os"
6 "strconv" 7 "strconv"
7 8
@@ -45,7 +46,7 @@ func init() { @@ -45,7 +46,7 @@ func init() {
45 } 46 }
46 47
47 filters.SecureKeyMap["token"] = "x-mmm-accesstoken" 48 filters.SecureKeyMap["token"] = "x-mmm-accesstoken"
48 - web.InsertFilter("/*", web.BeforeRouter, filters.AllowCors()) 49 + web.InsertFilter("/*", web.BeforeRouter, AllowCors())
49 web.InsertFilter("/*", web.BeforeRouter, filters.CreateRequstLogFilter(log.Logger)) 50 web.InsertFilter("/*", web.BeforeRouter, filters.CreateRequstLogFilter(log.Logger))
50 web.InsertFilter("/v1/web/*", web.BeforeExec, middleware.CheckAccessToken2()) 51 web.InsertFilter("/v1/web/*", web.BeforeExec, middleware.CheckAccessToken2())
51 web.InsertFilter("/v1/app/*", web.BeforeExec, middleware.CheckAccessToken2()) 52 web.InsertFilter("/v1/app/*", web.BeforeExec, middleware.CheckAccessToken2())
@@ -60,3 +61,19 @@ func init() { @@ -60,3 +61,19 @@ func init() {
60 )) 61 ))
61 //web.InsertFilterChain("/v1/*", middleware.CheckAccessToken) 62 //web.InsertFilterChain("/v1/*", middleware.CheckAccessToken)
62 } 63 }
  64 +
  65 +func AllowCors() func(ctx *context.Context) {
  66 + return func(ctx *context.Context) {
  67 + ctx.Output.Header("Access-Control-Allow-Methods", "OPTIONS,DELETE,POST,GET,PUT,PATCH")
  68 + //ctx.Output.Header("Access-Control-Max-Age", "3600")
  69 + //ctx.Output.Header("Access-Control-Allow-Headers", "*,x-mmm-version")
  70 + ctx.Output.Header("Access-Control-Allow-Headers", "Content-Type,X-Mmm-Accesstoken,X-Mmm-Devicetype,X-Mmm-Sign,X-Mmm-Timestamp,X-Mmm-Uuid,X-Mmm-Version")
  71 + ctx.Output.Header("Access-Control-Allow-Credentials", "true")
  72 + ctx.Output.Header("Access-Control-Allow-Origin", "*") //origin
  73 + if ctx.Input.Method() == http.MethodOptions {
  74 + // options请求,返回200
  75 + ctx.Output.SetStatus(http.StatusOK)
  76 + _ = ctx.Output.Body([]byte("options support"))
  77 + }
  78 + }
  79 +}