Raul
Raul

Reputation: 3081

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.

Upvotes: 1

Views: 9028

Answers (2)

seahorsepip
seahorsepip

Reputation: 4809

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 e.g. 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.

Upvotes: 2

user13268210
user13268210

Reputation:

This:

JSON.stringify(data);

will return

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

Upvotes: 0

Related Questions