zoukankan      html  css  js  c++  java
  • 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:*"},
            }))
  • 相关阅读:
    js 跨域问题 汇总
    js 数组的常用方法
    移动端web总结
    BitCoinCore配置文件解读
    同一台主机部署两个比特币钱包以及rpc服务的摘要
    ubuntu启动进程笔记
    C#按制定的环境编译替换不出对应的配置项的解决措施。
    【转】Javascript中使用WScript.Shell对象执行.bat文件和cmd命令
    C#执行javascript代码,执行复杂的javascript代码新方式
    linux小笔记
  • 原文地址:https://www.cnblogs.com/dannyyao/p/8047319.html
Copyright © 2011-2022 走看看