首页 > 后端开发 > Golang > 正文

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

王林
发布: 2024-02-06 11:00:11
转载
388 人浏览过

无法从 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学习者快速成长!