0

Currently losing my mind with CORS. I have a Vue.js app using Axios to post data to a Golang service (using Gorilla Mux and Handlers). Both applications are running on the same host.

The Axios call looks like this:

const axios = require('axios');

const options = {
    url: 'http://' + window.location.hostname + ':4002',
    method: 'POST',
    headers: {
        'Accept': 'application/json',
                    'Content-Type': 'application/json;charset=UTF-8'
    },
    data: {
        MyField1: "MyData1",
        MyField2: {
            MyField3: "MyData2"
        }
    }
};

axios(options)
    .then(response => {
        console.log(response.status);
    });

The Golang server looks like this:

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

    router := mux.NewRouter()
    router.HandleFunc("/", HandleRequest).Methods("POST", "OPTIONS")

    log.Fatal(http.ListenAndServe(":4002", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}

func HandleRequest(w http.ResponseWriter, r *http.Request) {
    ...
}

This is the result of hours of searching on how to get this working. I heavily referenced this answer and on testing with a CURL I receive the following (along with other redundant info):

< HTTP/1.1 200 OK
< Access-Control-Allow-Headers: X-Requested-With
< Access-Control-Allow-Origin: *
< Date: Sun, 29 Mar 2020 23:32:28 GMT
< Content-Length: 0

This leads me to believe everything should work fine, but I still see a 403 in Firefox's network viewer and the following in the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip>:4002/. (Reason: CORS request did not succeed).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip>:4002/. (Reason: CORS request did not succeed).
Error: Network Error

All information I can find leads me to believe that I should not be seeing this error at this point -- any help would be greatly appreciated.

user2741375
  • 35
  • 1
  • 7

1 Answers1

2

Finally fixed this by changing the Go code to this:

cors := handlers.CORS(
    handlers.AllowedHeaders([]string{"content-type"}),
    handlers.AllowedOrigins([]string{"*"}),
    handlers.AllowCredentials(),
)

router := mux.NewRouter()
router.HandleFunc("/", HandleRequest).Methods("POST", "OPTIONS")

router.Use(cors)

log.Fatal(http.ListenAndServe(":4002", (router)))
user2741375
  • 35
  • 1
  • 7