无法从 Golang 服务器中以 JavaScript 获取响应。

huangapple go评论91阅读模式
英文:

Cannot get response in JS from Golang server

问题

我有以下HTML代码:

<button onclick="clickListener()" id="form-button" type="button" class="btn btn-primary">点击</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("无法将响应数据转换为JSON")
        return
    }

    writer.Header().Set("Content-Type", "application/json")
    _, err = writer.Write(responseInJsonFormat)
    if err != nil {
        log.Println("无法将响应数据转换为JSON")
    }
}

如果我在浏览器中使用,我会得到JSON格式的响应数据,其中包含{IsAvailable: true, Message: "Available"}的数据。一切都正常工作。

但是由于某种原因,我无法在JS中获取这些数据。
我在JS中得到的响应只有以下内容:

无法从 Golang 服务器中以 JavaScript 获取响应。

没有头部或数据。
我该如何获取它呢?

谢谢!

英文:

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 browser, I get response in JSON format with data {IsAvailable: true, Message: "Available"}.<br>
Everything works well.

But for some reason I cannot get this data in JS.
All I get as a response in JS is:

无法从 Golang 服务器中以 JavaScript 获取响应。

There are no headers or data.<br>
How can I get it?<br>

Thank You!

答案1

得分: 0

Fetch返回一个Response对象,然后需要将其解析为可用的格式,例如JSON或文本。由于您想要JSON格式,您需要这样做:

fetch('/address')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log(e))

请参阅"使用Fetch API"获取更多详细信息。

英文:

Fetch returns a Response object, which then has to be parsed into a usable format, for example JSON or text. Since you want to have a JSON format, you would need to do this:

fetch(&#39;/address&#39;)
  .then(response =&gt; response.json())
  .then(data =&gt; console.log(data))
  .catch(e =&gt; console.log(e))

Take a look at "Using the Fetch API" for more details.

huangapple
  • 本文由 发表于 2023年3月24日 14:23:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75830570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定