英文:
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中得到的响应只有以下内容:
没有头部或数据。
我该如何获取它呢?
谢谢!
英文:
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:
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('/address')
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log(e))
Take a look at "Using the Fetch API" for more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论