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

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面