How to post a json request and recieve json respon

2020-05-11 00:12发布

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.

1条回答
Rolldiameter
2楼-- · 2020-05-11 00:28

Set Access-Control-Allow-Origin headers in your Golang code to allow request form cross origin

func index(w http.ResponseWriter, r *http.Request) {
    ans := answer{result: 30}
    fmt.Println(r)
    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)
    if err := json.NewEncoder(w).Encode(ans); err != nil {
        panic(err)
    }    
}

Also you can use CORS handler using this API for every request passing through router inside your main.

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/",index)
    handler := cors.Default().Handler(mux)
    fmt.Println("Server online at port localhost:8000")
    http.ListenAndServe(":8000", handler)
}
查看更多
登录 后发表回答