dongpao9437 2014-12-27 03:56
浏览 105
已采纳

Golang net / http请求正文始终为空

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.

  • 写回答

2条回答 默认 最新

  • dtdt0454 2014-12-29 00:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器