2016-07-14 2 views
1

は がそうする複数の方法を試みたし、奇妙な行動を取得して、モバイルデバイスからのOPTIONSメソッドを受け入れる必要があります。ゴリラハンドラを使用してモバイルからOPTIONSメソッドを許可する方法はありますか?

これをしようとしたとき、私はクライアントからの403を取得: (クライアントはPOSTOPTIONSを送信します)

import (
    "net/http" 

    "github.com/gorilla/handlers" 
    "github.com/gorilla/mux" 
) 

func main() { 
    r := mux.NewRouter() 
    r.HandleFunc("/users", UserEndpoint) 
    r.HandleFunc("/projects", ProjectEndpoint) 

    methods := handlers.AllowedMethods([]string{"OPTIONS", "DELETE", "GET", "HEAD", "POST"} 

    http.ListenAndServe(":8000", handlers.CORS(methods)(r)) 
} 

私は省略した場合methods:私は403を許可していない取得

 http.ListenAndServe(":8000", handlers.CORS()(r)) 

また、それで遊んGET方法削除:

methods := handlers.AllowedMethods([]string{"OPTIONS"} 

http.ListenAndServe(":8000", handlers.CORS(methods)(r)) 

をまだ(クロームDHC)

ブラウザに残り、クライアントからしようとしたとき 200 GETを得ることができるが、私は削除する場合OPTIONS

methods := handlers.AllowedMethods([]string{"DELETE", "GET", "HEAD", "POST"} 

http.ListenAndServe(":8000", handlers.CORS(methods)(r)) 

私は405

0123を取得

最初の例はゴリラハンドラのドキュメントに基づいています

この問題に関するアイデアはありますか?あなたはcors.goオプションを見れば

おかげ

答えて

0

は特別に処理されています

corsOptionMethod   string = "OPTIONS" 
... 

    if r.Method == corsOptionMethod { 
     if ch.ignoreOptions { 
      ch.h.ServeHTTP(w, r) 
      return 
     } 

     if _, ok := r.Header[corsRequestMethodHeader]; !ok { 
      w.WriteHeader(http.StatusBadRequest) 
      return 
     } 

     method := r.Header.Get(corsRequestMethodHeader) 
     if !ch.isMatch(method, ch.allowedMethods) { 
      w.WriteHeader(http.StatusMethodNotAllowed) 
      return 
     } 
... 

だから、405はhttp.StatusMethodNotAllowedなので、多分それはCORSリクエストヘッダではないでしょうか?

オプションを独立して処理するIngoreOptionsメソッドもあります。http://www.gorillatoolkit.org/pkg/handlers#IgnoreOptions - あなたのケースではうまくいくかもしれませんが、あなたはそれを無視したり、オプションを自分で処理することができます。

+0

'OPTIONS'を無視していて、次にそれらをcorsオプション矛盾で許可していませんか? –

2

あなたは本当に行われて要求を理解する必要があるが、私は同様の問題を抱えていたし、それを解決:

handlers.CORS(
     handlers.AllowedOrigins([]string{"*"}), 
     handlers.AllowedMethods([]string{"POST"}), 
     handlers.AllowedHeaders([]string{"Content-Type", "X-Requested-With"}), 
    )(router) 

(プリフライトを模倣する)私が行うために必要な要求だった:

curl -H "Origin: http://example.com" \ 
-H "Access-Control-Request-Method: POST" \ 
-H "Access-Control-Request-Headers: X-Requested-With" \ 
-X OPTIONS --verbose http://127.0.0.1:8080/products 

実際にはAllowedHeaders funcですべての違いがありました。それを追加するとすぐに、403エラーが消えました。

関連する問題