繁体   English   中英

如何使用 Axios 在 application/x-www-form-urlencoded 中编码 JSON 数据?

[英]How to encode JSON data in application/x-www-form-urlencoded using Axios?

我必须向 API 端点发出 post 请求,并且要求请求的正文在 application/x-www-form-urlencoded 中编码。

这是我目前正在做的事情:

  // Request data
  const data = {
    grant_type: "client_credentials",
  };

  // Request configuration
  const config = {
    method: "post",
    url,
    data,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization:
        "Basic " +
        Buffer.from(clientId + ":" + clientSecret).toString("base64"),
    },
  };

  return axios(config).then(.....

如您所见,我的数据为 JSON 格式,那么如何将其编码为 application/x-www-form-urlencoded 传递?

有任何想法吗? 谢谢你。

这个:

JSON.stringify(data);

将返回

'data = {"grant_type": "client_credentials"}'

application/x-www-form-urlencoded意味着您可以:

发送FormData body: axios post请求发送表单数据

或者在url查询字符串中发送数据: How to post query parameters with Axios?

您也可以将两者结合起来。

当 JSON 编码不符合要求(例如发送文件)时,通常使用此编码。 您可以在 json 字符串中发送一个文件,但这将是一个 base64 编码的文件作为字符串,这会增加大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM