71

我正在尝试使用一些要设置的表单参数创建一个 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
        }

在发布请求上设置这些表单参数的方法是否正确?

4

4 回答 4

125

您必须执行以下操作:

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);
    });
于 2015-08-01T03:49:01.193 回答
31

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

网络控制台截图


fetchAPI也是如此

fetch(url, {
  method: "POST",
  body: new URLSearchParams({
    your: "object",
    props: "go here"
  })
})
于 2021-04-14T07:31:53.017 回答
27

为什么要引入另一个库或模块来使用纯原生 JavaScript 做如此简单的事情?生成要在 POST 请求中提交的所需数据实际上是一行 JS。

// 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);
于 2019-04-17T04:01:24.160 回答
6

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

那么当然...

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

const response = await axios(options);

于 2021-02-20T17:05:28.077 回答