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.
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
}
}
First - you need to use schema in your handler:
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
}
But before it you need to specify in main "OPTIONS":
router.HandleFunc("/your_route/", your_method).Methods("POST", "OPTIONS")
It's because your browser doing 2 request - first to check ability to use some headers (Authorization for example) and next step is posting data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.