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 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下