I have created an API using Go. It's working fine in postman but not when consumed using javascript. When I post request using javascript I'm getting an error saying that Access-Control-Allow-Origin is set to null.
go API code:
package main
import (
"fmt"
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
)
type Calculate struct {
Operand1 string `json:"Operand1,omitempty"`
Operand2 string `json:"Operand2,omitempty"`
Operator string `json:"Operator,omitempty"`
}
type Answer struct {
Res string `json:"Res,omitempty"`
}
func do_Calculation(w http.ResponseWriter, r *http.Request) {
var cal Calculate
var ans Answer
fmt.Println("Request Reached")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
json.NewDecoder(r.Body).Decode(&cal)
// my stuff
// res := do_Operations(convertToFloat(cal.Operand1),convertToFloat(cal.Operand2),cal.Operator)
// ans = Answer{Res: floattostrwithprec(res, 4)}
json.NewEncoder(w).Encode(ans)
}
// main function to boot up everything
func main() {
router := mux.NewRouter()
router.HandleFunc("/calculate", do_Calculation).Methods("POST")
fmt.Println("Server online at port :8000")
log.Fatal(http.ListenAndServe(":8000", router))
}
javascript code:
var data = JSON.stringify({
"Operand1": "2.6",
"Operand2": "2.4",
"Operator": "+"
});
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:8000/calculate");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "POST");
xhr.withCredentials = true;
xhr.send(data);
error:
Failed to load http://127.0.0.1:8000/calculate: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.