2015-04-02 110 views
1

CORS我有一個AJAX調用谷歌的API的oauth2看起來是這樣的:啓用Golang回調函數

$(document).on('click', '#signup', function() { 
    var OAUTHURL  = 'https://accounts.google.com/o/oauth2/auth?'; 
    var SCOPE   = 'email profile'; 
    var STATE   = 'profile'; 
    var REDIRECT_URI = 'https://localhost:8080/callback'; 
    var RESPONSE_TYPE = 'token'; 
    var CLIENT_ID  = '554886359117-8icq0dc9halr8rjd6bdtqcmagrdql9lr.apps.googleusercontent.com'; 
    var _url   = OAUTHURL + 'scope=' + SCOPE + '&state=' + STATE + '&redirect_uri=' + REDIRECT_URI + '&response_type=' + RESPONSE_TYPE + '&client_id=' + CLIENT_ID; 
    $.ajax({ 
    type: "POST", 
    dataType: "text", 
    url: _url, 
    success: function(response) 
    { 
     console.log(response.url); 
    }, 
    error: function(error) 
    { 
     console.log("ERROR: ", error); 
    } 
    }); 
}); 

這應該回重定向到http://localhost/callback運行的服務器。

Redirect URIs: http://localhost:8080/callback 
Javascript Origins: http://localhost:8080 

我也有定義如下回調函數:

func init() { 
    r := mux.NewRouter() 

    r.HandleFunc("/", rootHandler) 
    r.HandleFunc("/callback", callbackHandler) 
    http.Handle("/", r) 
} 
func callbackHandler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprint(w, "I am sent back from the server!"+time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST")) 
} 

一切看起來都在調試模式下好,但我得到這個錯誤來自谷歌的API回:

的XMLHttpRequest無法加載 https://accounts.google.com/o/oauth2/auth?scope=email%20profile&state=profi ... d = 554886359117-8icq0dc9halr8rjd6bdtqcmagrdql9lr.apps.googleusercontent.com。 請求的 資源上沒有「Access-Control-Allow-Origin」標題。原因'http://localhost:8080'因此不允許 訪問。

我已經調整了一些,但我似乎無法找到我的方式。 對此有何想法?

回答

0

只需添加CORS頭到您的callbackHandler:

// make this configurable via command line flags, env var, or something 
var MyServerName = "https://localhost:8080" 

func callbackHandler(w http.ResponseWriter, r *http.Request) { 
    w.Header().Add("Access-Control-Allow-Origin", MyServerName) 

    fmt.Fprint(w, "I am sent back from the server!"+time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST")) 
} 
+0

我已經打了它不同的技巧,並沒有真正似乎來解決這個問題。 – 2015-04-02 11:04:58

+0

我的挑戰性問題是,如果問題來自我的AJAX調用通過線路發送的位置,還是我的回調處理程序無法處理來自Google的響應? – 2015-04-02 11:06:19

1

就像Not_a_Golfer說你的後端沒有設置正確的標題來響應。爲了在每種情況下處理CORS問題,我製作了這個包含路由器的小巧handler,以便您不必在每個回調中手動設置標題。

使用方法如下:

import "github.com/heppu/simple-cors" 

func init() { 
    r := mux.NewRouter() 
    r.HandleFunc("/", rootHandler) 
    r.HandleFunc("/callback", callbackHandler) 
    http.Handle("/", cors.CORS(r)) 
} 
func callbackHandler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprint(w, "I am sent back from the server!"+time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST")) 
}