即使 url-encoded (添加了 header),Axios 和 fetch 也会在 Golang 中给出空映射

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

我正在使用 axios 发送 http 请求(我也使用了 fetch 但它给出了相同的结果)。

axios.post("http://localhost:3000/login",
            {
                answer: 42
            },
            {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
            })

在我的 go 文件中,我正在记录响应

func post(req *http.Request, res http.ResponseWriter) {
    req.ParseForm()

    fmt.Println(req.Form)
}

日志如下:

map[{"answer":42}:[]]

但是我希望它如下所示:

map["answer":[42]]

(当我使用邮递员时得到这样的信息)

这有什么问题。

出站数据供参考


更新

我使用了请求(built-in 和 nodejs)以及 jQuery ajax。两者都很好。

只有 axios 和 fetch 无法正常工作

这是代码:

以下是我的jQuery代码

var settings = {
"async": true,
  "crossDomain": true,
  "url": "http://localhost:3000/login",
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
  },
  "data": {
    "answer": "42"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

但是,我仍然无法让 axios 和 fetch 工作。如果有人找到它,请更新答案

你需要这样的东西:

var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
});

您可以使用 params 配置选项设置查询字符串参数, 绝对有效:

axios.post("http://localhost:3000/login", "", {
    params: {answer: 42},
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})

要了解更多信息,请阅读这篇文章https://github.com/axios/axios/issues/350#issuecomment-227270046