【问题标题】:Axios Http client - How to construct Http Post url with form paramsAxios Http 客户端 - 如何使用表单参数构造 Http Post url
【发布时间】:2015-10-23 18:11:03
【问题描述】:

我正在尝试创建一个带有一些要设置的表单参数的 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"));

我正在尝试在 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 请求中设置这些表单参数的方法是否正确?

【问题讨论】:

    标签: javascript node.js axios


    【解决方案1】:

    如果您的目标运行时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'
    }))
    


    fetch API 也是如此

    fetch(url, {
      method: "POST",
      body: new URLSearchParams({
        your: "object",
        props: "go here"
      })
    })
    

    【讨论】:

    • 这应该是公认的答案。它不需要另一个库,也不依赖于您自己的库函数实现。简单而有效
    • URLSearchParams 已弃用
    • @yonadavbarilan no it isn't。什么让你有那个想法?可以提供参考吗?
    • @Phil 抱歉,我可能犯了一个错误或对其他 API 感到困惑,我实际上不记得我是如何得出这个结论的。我应该肯定提供参考:/
    【解决方案2】:

    为什么要引入另一个库或模块来使用纯原生 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);
    

    【讨论】:

    • 解决方案中缺少一步,对值进行编码。将 de ${val} 替换为 ${encodeURIComponent(val)}
    • 感谢 Giovane 的加入。我更新了代码。
    • @Michael Cole 为什么在编辑中删除方括号解构?它们是必要的。 answer by Nick Hanshaw 可能是因为您的更改而发布的。
    • 确实此编辑不正确且不起作用。根据尼克的工作答案编辑(可能这个在错误编辑之前工作)
    【解决方案3】:

    我同意 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);

    【讨论】:

      【解决方案4】:

      您必须执行以下操作:

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

      【讨论】:

      • 这对我有很大帮助,很简单querystring.stringify如果你使用application/x-www-form-urlencoded,你想要发送的json。
      • 对于 es6 使用 import qs from 'qs'; 来字符串化你的对象
      • 查询字符串已弃用?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多