Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert cURL to axios request

I am trying to convert a cURL request from here to Axios.

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 with 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.

like image 321
Martin Thompson Avatar asked Mar 27 '19 04:03

Martin Thompson


2 Answers

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();
like image 90
Martin Thompson Avatar answered Nov 16 '22 06:11

Martin Thompson


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

So make sure 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': 'application/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'
  })
};
like image 5
sudo soul Avatar answered Nov 16 '22 04:11

sudo soul