json - Golang net/http 请求 Body 总是空的

标签 json web go

我正在尝试将 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 {
       // handle error
    }
    log.Println(v)
}

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

$.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);
  }
});

发送内容的示例 URL:

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

更好地了解参数:

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

我已经尝试过 GET 和 POST 请求。

为什么我的 req.Body 从不解码?如果我尝试单独打印 req.Body,我也会看到 nil。

最佳答案

req.Body 确实是空的——所以,我会调用 req.ParseForm() 然后使用 req.Form 相反。 Body 不会获取绝对不在请求正文中的内容(例如,查询参数)。

关于json - Golang net/http 请求 Body 总是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664192/

相关文章:

java - Json 解析器捕获 Java 中的尾随逗号?

html - <link ref ="dns-prefetch"> 标签应该放在 <head> 网站的尽可能高的位置吗?

c# - Microsoft.VisualStudio.Web.Host.exe 使用 Visual Studio 2012/WIn7 锁定 32 位进程

google-app-engine - Go例程泄漏在哪里?

Goroutines 和依赖函数

javascript - JQuery UI 全尺寸日历 - 从 PHP 获取 JSON 数据

javascript - 如何在javaScript中添加变量作为json键

javascript - 使用javascript将json显示为html

javascript - 如何获取网站的背景颜色?

postgresql - 多行的 Golang 慢速扫描()