beego跨域請求配置

不說廢話json

在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請求,該請求若是收到響應(響應內容隨便),客戶端則纔會繼續發送請求函數

相關文章
相關標籤/搜索