简体   繁体   中英

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

I have to make a post request to an API endpoint and it is required that the body of the request is encoded in application/x-www-form-urlencoded.

Here is what I am currently doing:

  // 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(.....

As you can see, I have my data in JSON format, so how can I pass it encoded in application/x-www-form-urlencoded?

Any ideas? Thank you.

This:

JSON.stringify(data);

will return

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

application/x-www-form-urlencoded means you can:

Send FormData body: axios post request to send form data

Or send data in the url query string: How to post query parameters with Axios?

You can also combine both.

This encoding is often used when JSON encoding doesn't meet the requirements eg sending files. You could send a file in a json string but that would be a base64 encoded file as string which increases the size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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