首页 > 解决方案 > 如何使用 Axios 对 application/x-www-form-urlencoded 中的 JSON 数据进行编码?

问题描述

我必须向 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 编码传递?

有任何想法吗?谢谢你。

标签: javascriptnode.jshttpsaxioshttp-post

解决方案


这个:

JSON.stringify(data);

将返回

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

推荐阅读