Making golang Gorilla CORS handler work

后端 未结 7 1313
轮回少年
轮回少年 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:37

    You can get more details here: Why doesn’t Postman get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when my JavaScript code does? about this issue.

    Also try this handler: Go Cors Handler which should solve your issue. I find this much cleaner and easy to resolve the issue.

    package main
    
    import (
        "log"
        "net/http"
        "github.com/rs/cors"
        "github.com/gorilla/handlers"
        "github.com/gorilla/mux"
        "myApp/src/controllers"
    )
    
    func main() {
        ac := new(controllers.AccountController)
    
        router := mux.NewRouter()
        router.HandleFunc("/signup", ac.SignUp).Methods("POST")
        router.HandleFunc("/signin", ac.SignIn).Methods("POST")
    
        c := cors.New(cors.Options{
            AllowedOrigins: []string{"http://localhost:8000"},
            AllowCredentials: true,
        })
    
        handler := c.Handler(router)
        log.Fatal(http.ListenAndServe(":3000", handler)
    }
    

提交回复
热议问题