【问题标题】:How to allow OPTIONS method from mobile using gorilla handler?如何使用大猩猩处理程序允许来自移动设备的 OPTIONS 方法?
【发布时间】:2016-07-14 13:57:18
【问题描述】:

需要接受来自移动设备的 OPTIONS 方法, 尝试了多种方法并获得了奇怪的行为:

尝试此操作时,我从客户端收到 403: (客户端在POST之前发送OPTIONS

  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:

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

我得到 403 未授权

也玩过,去掉GET方法:

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

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

但仍然可以 在浏览器(chromes DHC)中从休息客户端尝试时获得200 GET

但如果我删除 OPTIONS:

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

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

我得到 405

第一个示例基于 gorilla handler 文档

对这个问题有什么想法吗?

谢谢

【问题讨论】:

    标签: go gorilla


    【解决方案1】:

    您确实需要了解正在提出的请求,但我遇到了类似的问题并通过以下方式解决了它:

    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 错误就消失了。

    【讨论】:

      【解决方案2】:

      如果你看cors.go选项是经过特殊处理的:

      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 - 也许这适用于您的情况,您可以忽略它,或者自己处理选项。

      【讨论】:

      • 不忽略OPTIONS,然后允许他们在cors选项中矛盾吗?
      猜你喜欢
      • 2017-06-28
      • 2018-12-01
      • 1970-01-01
      • 2021-12-29
      • 2018-06-08
      • 2014-03-15
      • 2023-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多