{console.log(response)}).catch"/> {console.log(response)}).catch">
Home >Backend Development >Golang >Unable to get JS response from Golang server
I have html:
<button onclick="clicklistener()" id="form-button" type="button" class="btn btn-primary">click</button>
js:
<script> const clicklistener = () => { console.log('clicklistener()') fetch("/address") .then(response => { console.log(response) }) .catch(e => { console.log(e) }) } </script>
go:
func Handler(writer http.ResponseWriter, request *http.Request) { response := jsonResponse{IsAvailable: true, Message: "Available"} responseInJsonFormat, err := json.MarshalIndent(response, "", " ") if err != nil { log.Println("cannot convert response data to JSON") return } writer.Header().Set("Content-Type", "application/json") _, err = writer.Write(responseInJsonFormat) if err != nil { log.Println("cannot convert response data to JSON") } }
If I use the browser, I receive a response in json format with the data {isavailable: true, message: "available"}.
everything is normal.
But for some reason I can't get these data in js. The response I get in js is:
No header or data.
How can I get it?
Thanks!
fetch returns a response
object which must then be parsed into a usable format such as json or text. Since you want json format, you need to do the following:
fetch('/address') .then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log(e))
See "Using the fetch api" for more details.
The above is the detailed content of Unable to get JS response from Golang server. For more information, please follow other related articles on the PHP Chinese website!