How to convert cURL to axios request

2019-08-21 21:33发布

问题:

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!

回答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();