Go Mux中间件没有使用我的CORS处理程序。

huangapple go评论73阅读模式
英文:

Go Mux Middlware not using my CORS handler

问题

mx := mux.NewRouter()

mx.Use(CorsHandler)

sch := mx.NewRoute().Subrouter()
sch.Use(middleware.ValidateSchoolToken)

teacher := mx.NewRoute().Subrouter()
teacher.Use(middleware.ValidateToken)

当代码运行时,不使用CorsHandler。

英文:
mx := mux.NewRouter()

mx.Use(CorsHandler)


sch := mx.NewRoute().Subrouter()
sch.Use(middleware.ValidateSchoolToken)

teacher := mx.NewRoute().Subrouter()
teacher.Use(middleware.ValidateToken)

CorsHandler is not used when the code runs

答案1

得分: 1

你是否在Methods调用中添加了http.MethodOptions?我在文档中找到了这个示例:

func main() {
    r := mux.NewRouter()

    // 重要提示:你必须为中间件指定一个OPTIONS方法匹配器以设置CORS头部
    r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions)
    r.Use(mux.CORSMethodMiddleware(r))
    
    http.ListenAndServe(":8080", r)
}

完整文档:https://pkg.go.dev/github.com/gorilla/mux#readme-handling-cors-requests

英文:

Have you added http.MethodOptions to your Methods call? I found this sample in the documentation:

func main() {
    r := mux.NewRouter()

    // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers
    r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions)
    r.Use(mux.CORSMethodMiddleware(r))
    
    http.ListenAndServe(":8080", r)
}

Full docs: https://pkg.go.dev/github.com/gorilla/mux#readme-handling-cors-requests

huangapple
  • 本文由 发表于 2021年7月10日 09:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/68324036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定