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

时间:2015-07-31 23:43:22

标签: javascript node.js axios

我正在尝试使用一些要设置的表单参数创建postHTTP请求。我正在使用带有节点服务器的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
        }

在帖子请求中设置这些形式参数的方法是否正确?

4 个答案:

答案 0 :(得分:72)

您必须执行以下操作:

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

答案 1 :(得分:7)

如果您的目标运行时 supports it,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"
  })
})

答案 2 :(得分:4)

我同意 jhickok 的观点,不需要引入额外的库,但是由于使用了 Object.entries,他们的代码不会产生正确的结果,您可能会看到以下内容:

<块引用>

"格式,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

那当然...

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

const response = await axios(options);

答案 3 :(得分:1)

为什么要引入另一个库或模块以使用纯原始JavaScript进行如此简单的操作?生成所需数据以提交到POST请求中实际上是JS的一行。

// es6 example

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

const data = Object.entries(params)
  .map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
  .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);