gpt4 book ai didi

javascript - 语言/Javascript : Empty postForm and decode(body) on JSON POST

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:15 26 4
gpt4 key购买 nike

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

This post展示了我用 Javascript 和 this post 发布我的 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));

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

我不确定从这里还能尝试什么。我应该更改什么才能使这项工作正常进行?

最佳答案

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

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

关于javascript - 语言/Javascript : Empty postForm and decode(body) on JSON POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com