{console.log(response)}).catch"/> {console.log(response)}).catch">

Home >Backend Development >Golang >Unable to get JS response from Golang server

Unable to get JS response from Golang server

王林
王林forward
2024-02-06 11:00:11437browse

无法从 Golang 服务器获取 JS 响应

Question content

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!


Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete