我正在嘗試將 JSON 數(shù)據(jù)從 javascript 頁(yè)面 POST 到 golang 服務(wù)器,但我無(wú)法在兩端使用 SO 接受的答案找到任何 JSON 數(shù)據(jù)的痕跡。這篇文章展示了我在 Javascript 中發(fā)布我的 JSON的方式,這篇文章展示了我嘗試在 Go 中處理這個(gè) JSON 的方式。//js json post sendvar 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 responsefunc 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 -> `{ }`}我不確定從這里還可以嘗試什么。我應(yīng)該改變什么才能使這項(xiàng)工作?
1 回答

九州編程
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
導(dǎo)出hat結(jié)構(gòu)Hat和 json 解碼的字段將起作用。
type Hat struct {
Hat string // Exported field names begins with capital letters
}
- 1 回答
- 0 關(guān)注
- 180 瀏覽
添加回答
舉報(bào)
0/150
提交
取消