dongweiben5229 2017-05-21 23:28
浏览 106
已采纳

CORS授权聚合物和goapp golang

I have polymer frontend which interact with goapp server. Everything works fine as long as I do not pass authorization token in header. Here is the code at Polymer side

<iron-ajax
      auto
        url="http://localhost:8080/ephomenotes"
        handle-as="json"
        last-response="{{response}}"
        headers="[[_computeHeader()]]"
        debounce-duration="300"></iron-ajax>

_computeHeader() {
        var token = localStorage.getItem("savedToken");
         var obj = {};
         obj.Authorization = "Bearer " + token;
         return obj;
        //return {"Authorization": "Bearer " + token};
      }

At golang server side

w.Header().Set("Access-Control-Allow-Credentials", "true")
if origin := r.Header.Get("Origin"); origin != "" {
    w.Header().Set("Access-Control-Allow-Origin", origin)
}
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

if r.Method == "OPTIONS" {
    return
}

Please note is I remove headers="[[_computeHeader()]]" from polymer code then it works..However with Authorization token it throws following error.

XMLHttpRequest cannot load http://localhost:8080/ephomenotes. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

Please help

  • 写回答

1条回答 默认 最新

  • dougong2306 2017-05-22 01:03
    关注

    Resolved the issue ..

    created new route for options

    r.OPTIONS("/ephomenotes", optionsheader)
    r.GET("/ephomenotes", env.EPHomePage)
    

    This is the new function.

    func optionsheader(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    
        w.Header().Set("Access-Control-Allow-Credentials", "true")
        if origin := r.Header.Get("Origin"); origin != "" {
            w.Header().Set("Access-Control-Allow-Origin", origin)
        }
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
        // w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    
    }
    

    However I am not sure, why this one worked?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?