Axios Http客户端 - 如何使用表单参数构建Http Post URL

103
我试图创建一个带有一些表单参数的postHTTP请求。我正在使用Node服务器上的axios。我已经有了一个构造url的java代码实现,如下所示:
JAVA CODE:
HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
            .path(TOKEN_ACCESS_PATH).build(getProperty("realm")));

List<NameValuePair> formParams = new ArrayList<NameValuePair>();

formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));

我正在尝试在axios中做同样的事情。

AXIOS实现:

axios.post(authServerUrl +token_access_path,
        {
                username: 'abcd', //gave the values directly for testing
                password: '1235!',
                client_id: 'user-client'
        }).then(function(response) {
            console.log(response); //no output rendered
        }

设置这些表单参数在POST请求中的方式是否正确?

5个回答

166
你必须做以下事情:
var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
    querystring.stringify({
            username: 'abcd', //gave the values directly for testing
            password: '1235!',
            client_id: 'user-client'
    }), {
      headers: { 
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }).then(function(response) {
        console.log(response);
    });

更新: 如果你正在使用es6,将import改为 import qs from 'qs';

3
这对我帮助很大,如果你使用application/x-www-form-urlencoded,只需简单地使用querystring.stringify来发送你想要发送的JSON数据。 - ThomasReggi
11
在 ES6 中,使用 import qs from 'qs'; 将你的对象转换为字符串。 - Ahmed Wahba
查询字符串已过时? - Melroy van den Berg
1
已经过时,请更新此内容。 - Hammad ul Hasan

69

如果您的目标运行时支持它, Axios可以接受一个URLSearchParams实例,这也将设置适当的Content-type头为application/x-www-form-urlencoded

axios.post(authServerUrl + token_access_path, new URLSearchParams({
  username: 'abcd', //gave the values directly for testing
  password: '1235!',
  client_id: 'user-client'
}))

network console screenshot


同样适用于fetch API。
fetch(url, {
  method: "POST",
  body: new URLSearchParams({
    your: "object",
    props: "go here"
  })
})

36

纯粹使用JavaScript就可以轻松地完成这样简单的任务,为什么还要引入其他库或模块呢?只需要一行JS代码即可生成所需的数据并提交POST请求。

// es6 example

const params = {
  format: 'json',
  option: 'value'
};

const data = Object.keys(params)
  .map((key) => `${key}=${encodeURIComponent(params[key])}`)
  .join('&');

console.log(data);
// => format=json&option=value

const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data,
  url: 'https://whatever.com/api',
};

const response = await axios(options);  // wrap in async function
console.log(response);

5
你的解决方案缺少一步,需要对数值进行编码。将 ${val} 替换为 ${encodeURIComponent(val)} - Giovane
2
谢谢你的贡献,Giovane。我已经更新了代码。 - jhickok
@Michael Cole,为什么你在编辑时删除了方括号解构?它们是必要的。Nick Hanshaw的回答可能是因为你的更改而发布的。 - Tyler Collier
确实,这次编辑是错误的且不起作用。根据Nick的可行答案进行了编辑(很可能在虚假编辑之前这个答案就已经起作用了)。 - Blacklight

9

我同意jhickok的观点,无需引入额外的库。然而由于使用了Object.entries,他们的代码将不会产生正确的结果,你会看到以下内容:

"format,json=0&option,value=1"

相反应该使用Object.keys。

const obj = {
  format: 'json',
  option: 'value'
};

const data = Object.keys(obj)
  .map((key, index) => `${key}=${encodeURIComponent(obj[key])}`)
  .join('&');
  
console.log(data); // format=json&option=value

Then of course...

const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data,
  url: 'https://whatever.com/api',
};

const response = await axios(options);


3
const body = new URLSearchParams();
body.append('param1', 'param1_value');
...
...
axios.post(url,body)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接