1. 程式人生 > >beego跨域請求配置

beego跨域請求配置

inf fun write ssa ins method 跨域 sage 跨域請求

不說廢話

在main函數前加入如下代碼

func init() {
//跨域設置
var FilterGateWay = func(ctx *context.Context) {ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
//允許訪問源
ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
//允許post訪問
ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers","Access-Control-Allow-Origin,ContentType,Authorization,accept,accept-encoding, authorization, content-type") //header的類型
ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
	}
	beego.InsertFilter("*", beego.BeforeRouter, FilterGateWay)
}
//路由設置
ns := beego.NewNamespace("/v1",
//	用於跨域請求
beego.NSRouter("*",&controllers.BaseController{},"OPTIONS:Options"),)
beego.AddNamespace(ns)

定義option函數回應預檢請求(controller中)
```
定義option函數回應預檢請求(controller中)
```go
// @Title test
// @Description 預檢
// @Success 200 {string} "hello world"
// @router / [options]
func (c *BaseController) Options() {
	c.Data["json"] = map[string]interface{}{"status": 200, "message": "ok", "moreinfo": ""}
	c.ServeJSON()
}
```

跨域請求是會先發送一個option請求,該請求如果收到響應(響應內容隨便),客戶端則才會繼續發送請求

beego跨域請求配置