我有 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” 了解更多详细信息。