drwn65609 2018-10-30 17:01
浏览 76
已采纳

即使使用url编码(添加标题),Axios和fetch也会在Golang中提供空映射

I'm using axios to send http requests ( i used fetch also but it gives the same result ).

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

In my go file I'm logging the response

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

    fmt.Println(req.Form)
}

The log is as follows :

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

However i want it to be as follows :

map["answer":[42]]

(I get such when i use postman)

What is the issue with this.

Outgoing data for reference

Outgoing data


UPDATE

I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.

Its just with axios and fetch which is not working

Here is the code :

  • request

    The following code using nodejs request

    var request = require("request"); 
    var options = { method: 'POST',
      url: 'http://localhost:3000/login',
      headers: 
       { 
         'cache-control': 'no-cache',
         'Content-Type': 'application/x-www-form-urlencoded' },
      form: { answer: '42' } };
    
    request(options, function (error, response, body) {
      if (error) throw new Error(error);
    
      console.log(body);
    });
    
  • jQuery ajax

The following is my jQuery code

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

However, I am still unable to get axios and fetch to work. If someone finds it please update the answer

  • 写回答

1条回答 默认 最新

  • doujia6433 2018-10-30 21:31
    关注

    You need something like this:

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

    You can set query string parameters using the params config option, It will definitely works:

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

    To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题