需要接受来自移动设备的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)中从rest客户端尝试时仍然可以获得200 GET
但如果我删除OPTIONS
methods := handlers.AllowedMethods([]string{"DELETE", "GET", "HEAD", "POST"}
http.ListenAndServe(":8000", handlers.CORS(methods)(r))
我得到405
第一个示例基于gorilla处理程序文档。
对这个问题有什么想法吗?
谢谢
发布于 2017-03-14 05:16:22
你真的需要了解正在发出的请求,但我遇到了类似的问题,并通过以下方法解决了它:
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
函数造成了所有的不同。一旦我添加了它,403
错误就消失了。
发布于 2016-07-15 00:23:39
如果你注意到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 --这可能适用于您的情况,您可以忽略它,或者自己处理选项。
https://stackoverflow.com/questions/38376226
复制相似问题