• beego api 服务允许跨域访问,解决前端访问报Access-Control-Allow-Origin问题


    背景:

      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:*"},
            }))
  • 相关阅读:
    「ROI 2019 Day1」运输 20/19
    「ROI 2018 Day 2」无进位加法
    「ROI 2018 Day 1」量子隐形传态
    「ROI 2018 Day 2」快速排序
    「ROI 2018 Day 1」Innophone (分块+斜率优化)
    「ROI 2017 Day 1」虎 (计算几何)
    [BJ United Round #3] 押韵 [学习笔记]
    「CEOI2020」象棋世界
    CF1375G
    CF1392(div1+div2)
  • 原文地址:https://www.cnblogs.com/dannyyao/p/8047319.html
Copyright © 2020-2023  润新知