How to post a json request and receive json response from "go server" (go language) using java script
I tried this
java script code:
var calculate = {
operand1 : null,
operand2 : null,
operator : null
};
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8000/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(calculate);
var response = (xhttp.responseText);
console.log(response);
}
UserAction();
go code:
package main
import ("fmt"
"net/http"
"encoding/json"
)
type answer struct {
result float64
}
func index(w http.ResponseWriter, r *http.Request) {
ans := answer{result: 30}
fmt.Println(r)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(ans); err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/",index)
fmt.Println("Server online at port localhost:8000")
http.ListenAndServe(":8000", nil)
}
And I am getting a error message
Failed to load http://localhost:8000/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.