How to convert cURL to axios request

19,807

Solution 1

I fixed it , I needed to put the values in parameters

import axios from "axios";

async function testApi() {
  try {
    const b = await axios.post("https://oauth.nzpost.co.nz/as/token.oauth2",
        params: {
          client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx",
          client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
          grant_type: "client_credentials"
        });
  } catch (error) {
    console.log(error);
  }
}

testApi();

Solution 2

As a reminder, curl -d is just a shorter way of saying curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d. It is POST request even though -X POST is not specified!

So make you configure your axios request as a POST request, while also ensuring your data is URL Encoded with the Content-Type header set to application/x-www-form-urlencoded. For example...

const response = await axios({
  url: 'example.com',
  method: 'post',
  headers: {
    'Content-Type': 'x-www-form-urlencoded'
  },
  // For Basic Authorization (curl -u), set via auth:
  auth: {
    username: 'myClientId',
    password: 'myClientSecret'
  },
  // This will urlencode the data correctly:
  data: new URLSearchParams({
    grant_type: 'client_credentials'
  })
};

 
Share:
19,807

Related videos on Youtube

Martin Thompson
Author by

Martin Thompson

Updated on September 15, 2022

Comments

  • Martin Thompson
    Martin Thompson over 1 year

    I'm obviously overlooking something here:

    I am trying to convert a cURL request to axios from Here .

    curl -d "grant_type=client_credentials\
    &client_id={YOUR APPLICATION'S CLIENT_ID} \
    &client_secret={YOUR APPLICATION'S CLIENT_SECRET}" \
    https://oauth.nzpost.co.nz/as/token.oauth2
    

    This works fine ( when I put my credentials in )

    I tried the following code:

    import axios from "axios";
    
    async function testApi() {
      try {
        const b = await axios.post("https://oauth.nzpost.co.nz/as/token.oauth2", {
          client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx",
          client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
          grant_type: "client_credentials"
        });
      } catch (error) {
        console.log(error);
      }
    }
    
    testApi();
    

    This fails. Error 400 . grant_type is required. I have tried putting it as a parameter , enclosing within a data: json block . I can't figure this out!