【问题标题】:How to handle Preflight requests for DELETE calls with Gorilla?如何使用 Gorilla 处理 DELETE 调用的预检请求?
【发布时间】:2021-07-26 03:47:52
【问题描述】:

我用Gorilla Web Toolkit 编写了一个简单的API,通过它的handlers 处理CORS 答案:

r := mux.NewRouter()
r.HandleFunc("/api/note", readHandler).Methods("GET")
r.HandleFunc("/api/note", writeHandler).Methods("POST")
r.HandleFunc("/api/note", deleteHandler).Methods("DELETE")
r.HandleFunc("/api/note", optionsHandler).Methods("OPTIONS")

optionsHandler 是

func optionsHandler(_ http.ResponseWriter, _ *http.Request) {
    return
}

我的理由是 Preflight 调用将使用 OPTIONS,但它唯一感兴趣的是相关的 CORS 标头。

GETPOST 工作正常,JavaScript fetch() 调用通过正确的标题。

DELETE 但是在 Preflight 调用中失败:Chrome DevTools 声明 DELETE + Preflight 调用失败并显示 CORS error,下一行是 Preflight OPTIONS 调用失败并显示 405(“方法不允许”)

为什么在处理方法时会出现此错误?以及如何解决?

【问题讨论】:

  • stackoverflow.com/questions/40985920/… - 您确定为GETPOST 发送预检吗?
  • @LarsChristianJensen:是的(我检查了标头,调用来自 JS)。我发现了问题并发布了答案。

标签: go cors gorilla http-status-code-405 mux


【解决方案1】:

我通过更新CORS() 调用解决了这个问题:

methods := handlers.AllowedMethods([]string{"OPTIONS", "DELETE", "GET", "HEAD", "POST", "PUT", "PATCH"})
origins := handlers.AllowedOrigins([]string{"*"})
headers := handlers.AllowedHeaders([]string{"Content-Type"})
log.Fatal(http.ListenAndServe("127.0.0.42:80", handlers.CORS(methods, origins, headers)(r)))

我认为(但我不确定)实际上修复了调用的是 headers 条目。

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 2015-04-07
    • 2015-04-02
    • 2018-11-12
    • 2020-10-13
    • 1970-01-01
    • 2016-02-17
    • 2017-06-25
    • 2021-09-26
    相关资源
    最近更新 更多