Golang网络/ http请求总是空的 [英] Golang net/http request Body always empty

查看:530
本文介绍了Golang网络/ http请求总是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着将JSON参数发送到我的服务器,并使用json.Decoder解析它们。我读过你应该能够从request.Body属性中获取查询参数。以下是我的服务器代码:

  func stepHandler(res http.ResponseWriter,req * http.Request){
var v interface {}
err:= json.NewDecoder(req.Body).Decode(& v)
if err!= nil {
//处理错误
}
log.Println(v)
}

每次我看到 2014/12/26 22:49:23< nil> (当然是diff时间戳)。我的客户端AJAX调用如下:

  $。ajax({
url:/ step,
方法:get,
data:{
steps:$(#step-size)。val(),
direction:$(#step-forward ).prop(checked)?1:-1,
单元格:JSON.stringify(画)

成功:函数(数据){
画= data;
redraw();
},
error:function(xhr){
console.log(xhr);
}
});

发送内容的示例网址:

 的http://本地主机:5000 /步骤= 1&安培;方向= 1&安培;单元=%5B%7B%22row%22%3A11%2C%22column%22%3A15%7D %2C%7B%22%22%3A12%2C%22列%22%3A15%7D%5D 

一个更好看的参数:

  {
steps:1,
direction: 1,
cells:[{row:11,column:15},{row:12,column:15}]
}

我尝试了GET和POST请求。



我的req.Body是否从未解码?如果我尝试单独打印req.Body,我也会看到零。

解决方案

req.Body 确实是空的 - 因此,我要做的是调用 req.ParseForm(),然后使用 req.Form 代替。 Body 不会获取绝对不在请求正文中的内容(例如查询参数)。


I'm trying to send JSON arguments to my server and parse them using json.Decoder. I've read that you should be able to get the query params from the request.Body property. The following is my server code:

func stepHandler(res http.ResponseWriter, req *http.Request) {
    var v interface{}
    err := json.NewDecoder(req.Body).Decode(&v)
    if err != nil {
       // handle error
    }
    log.Println(v)
}

Every time, I see 2014/12/26 22:49:23 <nil> (diff timestamps, of course). My client-side AJAX call is the following:

$.ajax({
  url: "/step",
  method: "get",
  data: {
    steps: $("#step-size").val(),
    direction: $("#step-forward").prop("checked") ? 1 : -1,
    cells: JSON.stringify(painted)
  },
  success: function (data) {
    painted = data;
    redraw();
  },
  error: function (xhr) {
    console.log(xhr);
  }
});

An example URL of what is sent:

http://localhost:5000/?steps=1&direction=1&cells=%5B%7B%22row%22%3A11%2C%22column%22%3A15%7D%2C%7B%22row%22%3A12%2C%22column%22%3A15%7D%5D

A nicer look at the params:

{
  steps: "1",
  direction: "1",
  cells: "[{"row":11,"column":15},{"row":12,"column":15}]"
}

I have tried with both GET and POST requests.

Why does my req.Body never decode? If I try to print req.Body alone, I also see nil.

解决方案

req.Body is indeed empty -- so, what I would do it call req.ParseForm() and then use req.Form instead. Body will not get stuff (such as, query parameters) that's definitely not in the request's body.

这篇关于Golang网络/ http请求总是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆