【问题标题】:GoLang/Javascript: Empty postForm and decode(body) on JSON POSTGoLang/Javascript:JSON POST 上的空 postForm 和解码(正文)
【发布时间】:2016-07-08 21:37:33
【问题描述】:

我正在尝试将 JSON 数据从 javascript 页面发布到 golang 服务器,但我无法在两端使用 SO 接受的答案找到 JSON 数据的任何痕迹。

This post 显示了我在 Javascript 中发布 JSON 的方式,this post 显示了我尝试在 Go 中处理这个 JSON 的方式。

//js json post send
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost:8080/aardvark/posts', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

var data = {hat: "fez"};
request.send(JSON.stringify(data));

The header below was set from this answer

//Go json post response
func reply(w http.ResponseWriter, r *http.Request) {

    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Credentials", "true")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")


    if err := r.ParseForm(); err != nil {
        fmt.Println(err);
    }

    //this is my first impulse.  It makes the most sense to me.
    fmt.Println(r.PostForm);          //out -> `map[]`  would be `map[string]string` I think
    fmt.Println(r.PostForm["hat"]);   //out -> `[]`  would be `fez` or `["fez"]`
    fmt.Println(r.Body);              //out -> `&{0xc82000e780 <nil> <nil> false true {0 0} false false false}`


    type Hat struct {
        hat string
    }

    //this is the way the linked SO post above said should work.  I don't see how the r.Body could be decoded.
    decoder := json.NewDecoder(r.Body)
    var t Hat   
    err := decoder.Decode(&t)
    if err != nil {
        fmt.Println(err);
    }
    fmt.Println(t);                  //out -> `{ }`
}

我不太确定还能从这里尝试什么。我应该改变什么来完成这项工作?

【问题讨论】:

  • 您使用r.Body 是对的。打印时它看起来如此奇怪的原因是您打印的结构可以让您阅读发布的内容(即io.Reader)而不是实际内容。
  • 这更有意义。谢谢
  • ParseForm 不起作用,因为它期望编码为 application/x-www-form-urlencoded 或 multipart/form-data,这与 json 不同

标签: javascript json post go


【解决方案1】:

导出结构体hat的字段Hat,json解码就可以了。

type Hat struct {
    Hat string // Exported field names begins with capital letters
}

【讨论】:

  • 有关详细信息,请参阅docs for Unmarshal:Unmarshal unmarshals into structs “首选完全匹配但也接受不区分大小写的匹配。Unmarshal 只会设置结构的导出字段”
  • 我读过 JSON.decode 应该用来代替 unmarshal。尽管它们看起来非常相似。 JSON.decode 是 unmarshal 基本功能的一种扩展吗?
猜你喜欢
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2021-07-15
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多