首頁 > 後端開發 > Golang > 主體

無法從 Golang 伺服器取得 JS 回應

王林
發布: 2024-02-06 11:00:11
轉載
389 人瀏覽過

无法从 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」 以了解更多詳細資訊。

以上是無法從 Golang 伺服器取得 JS 回應的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!