卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34258本站已运行391

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

无法从 golang 服务器获取 js 响应

问题内容

我有 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>

去:

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")
    }
}

如果我使用浏览器,我会收到 json 格式的响应,其中包含数据 {isavailable: true, message: "available"}。

一切正常。

但由于某种原因我无法在 js 中获取这些数据。 我在 js 中得到的响应是:

没有标题或数据。

我怎样才能得到它?

谢谢!


正确答案


fetch 返回一个 response 对象,然后必须将其解析为可用的格式,例如 json 或文本。由于您想要 json 格式,因此需要执行以下操作:

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

查看“使用 fetch api” 了解更多详细信息。

卓越飞翔博客
上一篇: 在 Go 中转换 Chrome 时间戳
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏