在目录routers中init.go文件中新增代码:
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowAllOrigins:true,
//AllowOrigins: []string{"https://192.168.0.102"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"token", "key", "Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
AllowCredentials:true,
}))
然后在controller中新增代码:
func (c *ApiController)Prepare() {
uri := c.Ctx.Input.URI()
serverUrl := beego.AppConfig.String("v2_api_server")
c.Url = serverUrl + uri[3:]
c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", c.Ctx.Request.Header.Get("Origin"))
}
参考文章:
网友评论