1

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.

Raul
  • 2,673
  • 1
  • 15
  • 52

2 Answers2

2

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.

seahorsepip
  • 4,519
  • 1
  • 19
  • 30
0

This:

JSON.stringify(data);

will return

'data = {"grant_type": "client_credentials"}'
  • 1
    And... What's the point of this? The OP wanted [application/x-www-form-urlencoded](https://dev.to/sidthesloth92/understanding-html-form-encoding-url-encoded-and-multipart-forms-3lpa#url-encoded-form), not [JSON](https://www.json.org/json-en.html). – Take-Some-Bytes Sep 10 '20 at 19:30