2017-09-21 176 views
1

我已經使用gorilla/muxrs/cors設置了我的Go後端。當我嘗試發送包含自定義標題(Bearer)的請求時,它將失敗。golang預檢請求錯誤

我的服務器設置是這樣的:

 router := mux.NewRouter().StrictSlash(true) 
router.HandleFunc("/users", GetUsers).Methods("GET") 
router.HandleFunc("/", GetUsers).Methods("GET") 
router.HandleFunc("/tweets", GetTweets).Methods("GET") 
router.HandleFunc("/login", Login).Methods("POST") 
router.HandleFunc("/profile/tweets", ProfileTweets).Methods("GET") 

c := cors.New(cors.Options{ 
    AllowedOrigins: []string{"*"}, 
    AllowedMethods: []string{"GET", "POST", "PATCH"}, 
    AllowedHeaders: []string{"Bearer", "Content_Type"},}) 

handler := c.Handler(router) 
log.Fatal(http.ListenAndServe(":8080", handler)) 

我曾嘗試過各種其他解決方案(如在Methods通話將OPTIONS 爲此我試圖通過Bearer令牌是/profile/tweets端點。端點。

我不知道該如何繼續gorilla/muxrs/cors中添加預檢要求的條款。

我得到的實際錯誤:

提取API無法加載http://localhost:8080/profile/tweets。響應 預檢申請未通過訪問控制檢查:沒有 「訪問控制允許來源」標頭出現在請求 資源。原因'http://localhost:4200'因此不允許 訪問。如果一個不透明的響應滿足您的需求,請將請求的 模式設置爲'no-cors'以禁用CORS來獲取資源。

謝謝!

+0

是不是'內容Type'而不是'Content_Type'? –

+0

@FrançoisP。這可能是它..我剛剛解決了它,我還需要添加'OptionsPassthrough' –

+0

有用的信息:) –

回答

2

我剛剛解決了這個問題。我不得不通過@Francois P.指出

此外,我不得不添加OptionsPassthroughAllowedHeaders一個錯字和OPTIONS方法,像這樣:

 router.HandleFunc("/profile/tweets", ProfileTweets).Methods("GET","OPTIONS") 

c := cors.New(cors.Options{ 
    AllowedMethods: []string{"GET","POST", "OPTIONS"}, 
    AllowedOrigins: []string{"*"}, 
    AllowCredentials: true, 
    AllowedHeaders: []string{"Content-Type","Bearer","Bearer ","content-type","Origin","Accept"}, 
    OptionsPassthrough: true, 
}) 
+0

標記爲已接受? – PieOhPah

+0

@PieOhPah我會但我必須等待一段時間;-) –