需要接受来自移动设备的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))
}
如果我省略方法
:
http.ListenAndServe(":8000", handlers.CORS()(r))
我收到 403 未授权
也尝试过,删除了 GET
方法:
methods := handlers.AllowedMethods([]string{"OPTIONS"}
http.ListenAndServe(":8000", handlers.CORS(methods)(r))
但是还是可以的
从浏览器中的其余客户端尝试时获得 200 GET
(chromes DHC)
但是如果我删除OPTIONS
:
methods := handlers.AllowedMethods([]string{"DELETE", "GET", "HEAD", "POST"}
http.ListenAndServe(":8000", handlers.CORS(methods)(r))
我得到 405
第一个示例基于 Gorilla 处理程序文档
关于这个问题有什么想法吗?
谢谢
最佳答案
您确实需要了解所提出的请求,但我遇到了类似的问题并通过以下方式解决了它:
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
错误就消失了。
关于go - 如何使用 gorilla 处理程序允许移动设备上的 OPTIONS 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38376226/