美文网首页goer
beego 接口跨域请求配置

beego 接口跨域请求配置

作者: 彭积祥_1c29 | 来源:发表于2019-05-10 10:53 被阅读0次

在目录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"))

}

参考文章:

1)《没错,就是Access-Control-Allow-Origin,跨域》

2)《如何解决出现AXIOS的Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response》

相关文章

网友评论

    本文标题:beego 接口跨域请求配置

    本文链接:https://www.haomeiwen.com/subject/fvuooqtx.html