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

首頁  >  文章  >  後端開發  >  無法從 Golang 伺服器取得 JS 回應

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

王林
王林轉載
2024-02-06 11:00:11373瀏覽

无法从 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刪除