Sankar P Sankar P - 24 days ago 19
Javascript Question

CORS on golang server & javascript fetch frontend

I have a golang HTTP server with code like:

http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
log.Println("New incoming request")

// Authenticate
if u, p, ok := r.BasicAuth(); ok {
log.Println("Success")
return
}
log.Println("Failed")


I call this HTTP endpoint from a JS frontend, a react app deployed on port 3000, using code:

fetch('http://localhost:8080/login', {
method: 'post',
headers: {
'Authorization': 'Basic ' + btoa(authHeader),
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
body: 'A=1&B=2'
})
.then(function (response) {
console.log("Authentication Success")
})
.catch(function (err) {
console.log("Authentication fail", err)
});


The above code fails with the following logs.

On the server side:

New incoming request
Failed


On the browser, in the developer tools logs:

Fetch API cannot load http://localhost:8080/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


Can someone help fix the authentication problem ? I am not sure if I am missing something related to CORS on the server side or doing bad authentication on the client side. Any help ? Thanks.

Answer

The Access-Control-Allow-Origin: * has to be sent from the server, not by the client. Assuming you are in a standard net/http handler function, try this code:

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    if (r.Method == "OPTIONS") {
        w.Header().Set("Access-Control-Allow-Headers", "Authorization") // You can add more headers here if needed
    } else {
        // Your code goes here
    }
}
Comments