Unable to get JS response from Golang server

王林
Release: 2024-02-06 11:00:11
forward
388 people have browsed it

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

Question content

I have html:

<button onclick="clicklistener()" id="form-button" type="button" class="btn btn-primary">click</button>
Copy after login

js:

<script>
        const clicklistener = () => {
            console.log('clicklistener()')

            fetch("/address")
                .then(response => {
                    console.log(response)
                })
                .catch(e => {
                    console.log(e)
                })
        }
   </script>
Copy after login

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")
    }
}
Copy after login

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))
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!