config CORS in Gorilla Mux: 403 error on POST requ

2019-02-20 18:07发布

问题:

I have an API, currently am trying to consume one of its endpoints. The endpoint is for POST requests, the endpoint is working as expected. The API is running in the cloud, I tested it with curl and it was perfect, then from my react app I was trying to consume it but I get 403 status code.

Watching in the console of the browser I see that I get that error on a OPTIONS request, and the POST never get done. Here is a screenshot of the result displayed in the console:

Then, I made a simple HTML file with a form, there I placed the required inputs, and the action pointing to this endpoint and it worked pretty well. Then, I don't know where would be the error? I have enabled CORS in the API

In the API I am using Gorilla/mux and I have something like this:

// Set up a router and some routes
    r := mux.NewRouter()
    r.HandleFunc("/", handleHome)
    //some other routes

    headersOk := handlers.AllowedHeaders([]string{"*"})
    originsOk := handlers.AllowedOrigins([]string{"*"})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

    // Start http server
    port := fmt.Sprintf(":%d", SomePort)
    http.ListenAndServe(port, handlers.CORS(originsOk, headersOk, methodsOk)(r))

Using:

"github.com/gorilla/mux"
"github.com/gorilla/handlers"

The message that I am getting in the browser is (in Spanish):

Solicitud desde otro origen bloqueada: la política de mismo origen impide leer el recurso remoto en https://miURL (razón: falta la cabecera CORS 'Access-Control-Allow-Origin').

In English: basically the server is rejecting the request because the CORS header is not present.

So, what have I done wrong in my router configuration?

回答1:

With rs/cors you should solve CORS issues pretty easily.

On your server.go

package main

import (
    . . .       
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "github.com/rs/cors"
    "../myhandler"
)

func main() {

fmt.Println("Settin up server, enabling CORS . . .")

  c := cors.New(cors.Options{
      AllowedOrigins: []string{"*"}, // All origins
      AllowedMethods: []string{"GET"}, // Allowing only get, just an example
  })

  router := mux.NewRouter()
  // Example handler
  router.HandleFunc("/test", myhandler.TestHandler())
  http.Handle("/", router)

  // Bind to port 8000 and pass our router in and pass the cors Handler
  log.Fatal(http.ListenAndServe(":8000"), c.Handler(router)))

  fmt.Println("Server is ready and is listening at port :8000 . . .")

}

And on your testhandler.go, let's suppose you want to accept Content-Type: application/json

. . .

func TestHandler func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    return
}


回答2:

Solution :)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    //this is the solution
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

OR

   upgrader.CheckOrigin = func(r *http.Request) bool { return true } //this :)
   ws, err := upgrader.Upgrade(w,r,nil)