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.
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();
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'
})
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With