【Go】beego跨域设置方法
golagn beego
Access to CSS stylesheet at ‘xxx’ from origin ‘xx’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
请求后台信息,弹出上面错误提示,就是不同域名下引起的跨域问题。
跨域问题不止要求一级域名相同,二级域名也要求相同,例如 a.tl.beer 和 b.tl.beer 就属于不同域的,同样的http://请求https://也会引起跨域问题
允许指定域名发请求
可以加到入口main.go,也可加到任一控制器 init()函数中
package main
import (
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/filter/cors"
)
func main() {
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
// 允许指定源
AllowOrigins: []string{"https://a.tl.beer", "http://a.tl.beer", "https://b.tl.beer", "http://b.tl.beer"},
// 可选参数"GET", "POST", "PUT", "DELETE", "OPTIONS" (*为所有)
AllowMethods: []string{"GET", "POST", "PUT"},
// 指的是允许的Header的种类
AllowHeaders: []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
// 公开的HTTP标头列表
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
}))
beego.Run()
}
使用通配符,允许同一个域名下的所有二级域名
package main
import (
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/filter/cors"
)
func main() {
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
AllowOrigins: []string{"https://*.tl.beer"},
}))
beego.Run()
}
使用AllowAllOrigins,一次到位,允许所有域名请求!
package main
import (
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/filter/cors"
)
func main() {
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
// 允许所有源访问
AllowAllOrigins: true,
}))
beego.Run()
}