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

即使使用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

    点赞 打赏 评论

相关推荐 更多相似问题