我的 golang 应用程序无法解码来自浏览器的表单,但在使用 curl 和 httpie 时成功。鉴于此代码: type Member struct { Username string `json:"username"` Email string `json:"email"` Password string `json:"password"` } func Register(w http.ResponseWriter, r *http.Request, p httprouter.Params) { var t Member json.NewDecoder(r.Body).Decode(&t) log.Println(t.Username) log.Println(t.Email) log.Println(t.Password) w.WriteHeader(204) }这打印!curl -H "Content-Type: application/json" -X POST -d '{"username":"cesco","email":"cesco@gmail.com","password":"password"}' http: //本地主机:5000/注册还有这个!http -v -j --form POST localhost:5000/register username="cesco" email="cesco@gmail.com" password="sadsa"这不<form id="register" action="register" method="post"> <input type="text" name="username"><br> <input type="email" name="email"><br> <input type="password" name="password"><br> <input type="submit" value="Submit"></form>既不是这个var data = $('#register').serialize();$.ajax({ url: 'register', // php script to retern json encoded string data: data, // serialized data to send on server beforeSend: function (xhr) { xhr.setRequestHeader("Content-type", "*/*"); }, dataType: 'json', // set recieving type - JSON in case of a question type: 'POST', // set sending HTTP Request type async: false, success: function (data) { // callback method for further manipulations }, error: function (data) { // if error occured }});
1 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
您的 curl 示例发布了一个带有Content-Type: application/json
. 浏览器不会以某种方式将 html 表单编码为 json。正如您在日志中看到的,您收到了Content-Type: application/x-www-form-urlencoded
如果您想从表单中获取值,请使用Request.FormValue
, 或Request.PostFormValue
- 1 回答
- 0 关注
- 321 浏览
添加回答
举报
0/150
提交
取消