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

mmr*_*raj 43 javascript node.js axios

我正在尝试创建一个postHTTP请求,其中包含一些要设置的表单参数.我正在使用带有节点服务器的axios.我已经有一个构建url的java代码实现,如下所示:

JAVA代码:

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"));
Run Code Online (Sandbox Code Playgroud)

我想在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
        }
Run Code Online (Sandbox Code Playgroud)

在邮政要求上设置这些形式参数的方法是否正确?

小智 77

您必须执行以下操作:

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);
    });
Run Code Online (Sandbox Code Playgroud)

  • 对于 es6 使用 `import qs from 'qs';` 来字符串化你的对象 (6认同)
  • 这对我帮助很大,如果您使用的是“application/x-www-form-urlencoded”,那么简单的“querystring.stringify”就是您想要发送的json。 (2认同)

Phi*_*hil 15

如果您的目标运行时支持它,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'
}))
Run Code Online (Sandbox Code Playgroud)

网络控制台截图


这同样适用于该fetchAPI

fetch(url, {
  method: "POST",
  body: new URLSearchParams({
    your: "object",
    props: "go here"
  })
})
Run Code Online (Sandbox Code Playgroud)


jhi*_*kok 7

为什么要引入另一个库或模块以使用纯原始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);
Run Code Online (Sandbox Code Playgroud)

  • 您的解决方案中缺少一个步骤,对值进行编码。将 de `${val}` 替换为 `${encodeURIComponent(val)}` (5认同)
  • 感谢您添加 Giovane。我更新了代码。 (2认同)

Nic*_*haw 5

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

“格式,json=0&选项,值=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
Run Code Online (Sandbox Code Playgroud)

那么当然...

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

const response = await axios(options);
Run Code Online (Sandbox Code Playgroud)