Making golang Gorilla CORS handler work

后端 未结 7 1314
轮回少年
轮回少年 2020-12-14 01:13

I have fairly simple setup here as described in the code below. But I am not able to get the CORS to work. I keep getting this error:

XML

7条回答
  •  生来不讨喜
    2020-12-14 01:19

    After declaring the mux object, add the accessControlMiddleware as a middleware to the declared object.

    func main(){
      ac := new(controllers.AccountController)
    
        router := mux.NewRouter()
        router.Use(accessControlMiddleware)
        router.HandleFunc("/signup", ac.SignUp).Methods("POST")
        router.HandleFunc("/signin", ac.SignIn).Methods("POST")
        http.ListenAndServe(":3000", corsOpts.Handler(router))
    }
    
    // access control and  CORS middleware
    func accessControlMiddleware(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                w.Header().Set("Access-Control-Allow-Origin", "*")
                w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS,PUT")
                w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type")
    
                    if r.Method == "OPTIONS" {
                        return
                    }
    
                    next.ServeHTTP(w, r)
                })
            }
    

提交回复
热议问题