GoLang/Javascript: 在 JSON POST 请求中,如何处理空的 postForm 并解码 body?

huangapple go评论109阅读模式
英文:

GoLang/Javascript: Empty postForm and decode(body) on JSON POST

问题

我正在尝试从JavaScript页面向Golang服务器POST JSON数据,但是我无法在两端使用SO接受的答案中找到任何JSON数据的痕迹。

这篇帖子展示了我在JavaScript中发布JSON的方式,而这篇帖子展示了我在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));

下面的标头是从这个答案中设置的

//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 -> `{ }`

}

我真的不确定接下来还能尝试什么。我应该做出什么改变才能使其工作?

英文:

I'm trying to POST JSON data from a javascript page, into a golang server, but I'm unable to find any trace of the JSON data using the SO accepted answers on both ends.

This post shows the way I'm posting my JSON in Javascript and this post shows the way I'm trying to process this JSON in Go.

//js json post send
var request = new XMLHttpRequest();
request.open(&#39;POST&#39;, &#39;http://localhost:8080/aardvark/posts&#39;, true);
request.setRequestHeader(&#39;Content-Type&#39;, &#39;application/json; charset=UTF-8&#39;);
    
var data = {hat: &quot;fez&quot;};
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(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
    w.Header().Set(&quot;Access-Control-Allow-Credentials&quot;, &quot;true&quot;)
    w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With&quot;)
    w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, OPTIONS, GET, PUT&quot;)


    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 -&gt; `map[]`  would be `map[string]string` I think
    fmt.Println(r.PostForm[&quot;hat&quot;]);   //out -&gt; `[]`  would be `fez` or `[&quot;fez&quot;]`
	fmt.Println(r.Body);              //out -&gt; `&amp;{0xc82000e780 &lt;nil&gt; &lt;nil&gt; 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&#39;t see how the r.Body could be decoded.
 	decoder := json.NewDecoder(r.Body)
    var t Hat   
    err := decoder.Decode(&amp;t)
    if err != nil {
        fmt.Println(err);
    }
    fmt.Println(t);                  //out -&gt; `{ }`
}

I'm not really sure what else to try from here. What should I change to make this work?

答案1

得分: 3

将结构体Hat的字段hat导出,这样JSON解码就可以正常工作。

type Hat struct {
    Hat string // 导出的字段名以大写字母开头
}
英文:

Export the field hat of the struct Hat and json decoding would work.

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

huangapple
  • 本文由 发表于 2016年3月22日 13:41:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/36146950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定