How to handle preflight CORS requests on a Go server

前端 未结 5 895
时光说笑
时光说笑 2020-12-09 01:48

So I\'m writing this RESTful backend in Go, which will be called with cross-site HTTP requests, i.e. from content served by another site (actually, just another port, but th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 01:55

    Well, nothing worked from me from my Vue.js application so I did this.

    cors := cors.New(cors.Options{
            AllowedOrigins:   []string{"*"}, //viper.GetString("ORIGIN_ALLOWED")
            AllowedHeaders:   []string{"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token", "Authorization"},
            AllowedMethods:   []string{"GET", "PATCH", "POST", "PUT", "OPTIONS", "DELETE"},
            Debug:            true,
            AllowCredentials: true,
        })
    
    cors.Handler(corsMiddle())
    
    func corsMiddle() http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
            if request.Method == "OPTIONS" {
                w.WriteHeader(http.StatusOK)
            }
        })
    }
    

提交回复
热议问题