背景:

  golang做了个简单服务,前端get请求拿数据,报错:No 'Access-Control-Allow-Origin' header is present on the requested

如何解决:


1、据说ajax可以解决(本人没试过)

2、服务端设置,允许跨域请求:在路由中添加如下设置即可

 

  beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
        AllowAllOrigins:  true,
        AllowMethods:     []string{"*"},
        AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin"},
        ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin"},
        AllowCredentials: true,
    }))

 

特别感谢:https://studygolang.com/articles/7330

==================================2018/1/6================================================

今天再次碰到:Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response

没有仔细看错误信息,又卡了一个多小时。很明显是Content-Type不允许嘛,那就在 AllowHeaders把Content-Type加上就好了

哎哎-------被坑的弱智了

AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "content-type"}

================================2018/1/9==================================================

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

很明显,AllowCredentials: true的时候,返回header的Access-Control-Allow-Origin不能为*;那如何配???

答案:不能用AllowAllOrigins: true,必须指定可访问域名AllowOrigins

beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
                //AllowAllOrigins:  true,
                AllowMethods:     []string{"*"},
                AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "content-type"},
                ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin"},
                AllowCredentials: true,
                AllowOrigins: []string{"http://10.*.*.*:*","http://localhost:*","http://127.0.0.1:*"},
        }))

 

posted on 2017-12-16 18:44  蛋尼  阅读(2546)  评论(0编辑  收藏  举报