Converting Curl to Nodejs Axios - Obtaining an Access Token - node.js

I am currently using curl in order to obtain an access token so I can consume an api with said token. The curl command I use is as follows:
curl --user <client_id>:<client_secret> https://api.ed-fi.org/v3/api/oauth/token --data 'grant_type=client_credentials'
It works and all...but instead of curling I want to utilize the axios library to get this access token instead.
Here's what I have but it doesn't work.
const buff = new Buffer.from('<client_id>:<client_secret>';
const base64data = buff.toString('base64');
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`
},
data: { 'grant_type': 'client_credentials' }
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
I can't figure out what I'm missing or doing wrong?

You should change Content-Type (default for axios is JSON) and pass body just like you did in case of curl:
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'grant_type=client_credentials'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});

Related

Make Request With Node.JS To Change Vanity Discord

How can I change the vanity url code in Discord? My current code returns a 401 error.
Code:
const fetch = require("node-fetch");
setTimeout(async () => {
await fetch('https://www.discord.com/api/v9/guilds/serverID/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"terbo1"
})
})
.then(async res => await res.json())
.then(json => { console.log(json);});
Response:
{ message: '401: Unauthorized', code: 0 }
I don't understand why you need setTimeout however you were using the wrong HTTP method on the request: the correct method is PATCH.
Additionally, payload isn't an option on the Fetch API, use body instead.
const fetch = require("node-fetch");
const endpoint = `https://www.discord.com/api/v10/guilds/${SERVER_ID}/vanity-url`;
await fetch(endpoint,{
method: "PATCH",
headers: {
Authorization: `Bot ${client.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo1",
}),
});
Edit: As of 01/12/2022 (12/01/22) Discord have now disabled this ability for bots to "manipulate" this request, however, the above script can be used on a User-Account, there are risks of being banned doing so, so it is NOT recommended, use at your own risk.

Axios 400 Bad Request Cognito JWT generation in Node Js

I am trying to create Cognito JWtoken via POST call with axios in Lambda function using node js , but i am getting error 400 bad request.
In parallel it is working fine in Postman.
Code :
await axios.post('https://smartfactoryfabric-dev.auth.us-east-1.amazoncognito.com/oauth2/token', {
grant_type: grantType, // This is the body part
redirect_uri: redirectURI,
client_id: clientid,
code: 'fb06a2dd-XXXXXXXXX-f186c6302806'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authValue
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response)
});
You need to URL encode the body of your request into a single string. You can use querystring.stringify to do this.
let data = querystring.stringify({
grant_type: 'grantType',
redirect_uri: 'redirectURI',
client_id: 'clientid',
code: 'fb06a2dd-XXXXXXXXX-f186c6302806'
})
=> 'client_id=clientid&code=fb06a2dd-XXXXXXXXX-f186c6302806&grant_type=grantType&redirect_uri=redirectURI'
Then your request will look like this:
await axios.post('https://smartfactoryfabric-dev.auth.us-east-1.amazoncognito.com/oauth2/token',
data,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + authValue
}
})

How to rewrite this cURL command to axios code

I need to call the propublica API the call example they have is using cURL:
-H "X-API-Key: PROPUBLICA_API_KEY"
How can i rewrite it in axios.
I tried this and does not work, get an undefined response.
axios.get('"https://api.propublica.org/congress/v1/members/{house}/{FL}/current.json/X-API-Key/APIKEY '),
]).then(axios.spread((response1, response2) => {
console.log(response1.data.url);
})).catch(error => {
console.log(error);
}); ```
the -H option is to pass the option as a header, not as a query parameter or as a part of the URL. You would have to do something like this instead:
axios.get(url, { headers: { 'X-API-Key': headerKey } })
Using the RESTClient Extension for firefox, this worked for me:
https://api.propublica.org/congress/v1/116/senate/members.json
with in Header X-API-Key:my-personal -key.
So using axios, you may use:
let url = 'https://api.propublica.org/congress/v1/116/senate/members.json';
axios.get(url,
{
headers: {
'X-API-Key': headerKey
}
}
)
.then (res=>console.log(res))
.catch(err => console.log(err));
This is working, thanks for the answers.
const axios = require('axios');
axios.request({
url: "https://api.propublica.org/congress/v1/members/house/FL/current.json",
headers: { 'X-API-Key': "API-KEY" },
method: 'get'
}).then(response => {
// console.log(response.data.url);
console.log(response.data)
}).catch(error => {
console.log(error);
});

Try to fetch Instagram access token with all required params but still get an error code 400

This is the server side code that tried to make a POST request to Instagram to get an access token
app.get('/instagram/json', (req, res) => {
axios({
method: 'post',
url: 'https://api.instagram.com/oauth/access_token',
data: {
'client_id': instagramClientId,
'client_secret': instagramClientSecret,
'grant_type': 'authorization_code',
'redirect_uri': 'http://localhost:3000',
'code': instagramCode
}
}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
});
This is the error response I get. It tells me that "client_id" is required despite I clearly have provided it.
data:
{ error_type: 'OAuthException',
code: 400,
error_message: 'You must provide a client_id' } } }
Here is a solution:
const insta_form = new URLSearchParams();
insta_form.append('client_id', 'xxx');
insta_form.append('client_secret', 'xxx');
insta_form.append('grant_type', 'authorization_code');
insta_form.append('redirect_uri', 'xxx');
insta_form.append(
'code',
'xxx'
);
await axios({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: insta_form,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err.response);
});
}
import axios from 'axios'
import {stringify} from 'qs'
const response = await axios({
method: "post",
url: "https://api.instagram.com/oauth/access_token",
data: stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
redirect_uri: REDIRECT_URL,
code
}),
headers: { "Content-Type": 'application/x-www-form-urlencoded' },
})
Late, but since there's not a good answer on the web and took me a while:
You'd have to wrap your body inside a form-data before providing it to fetch-node's post.
Install form-data: npm install --save form-data
then:
const formData = require("form-data");
const insta_form = new formData();
insta_form.append("client_id", your client id);
insta_form.append("client_secret", your client secret);
insta_form.append("grant_type", "authorization_code");
insta_form.append("redirect_uri", your redirect uri);
insta_form.append("code", user code);
const shortTokenRes = await fetch(
"https://api.instagram.com/oauth/access_token",
{
method: "POST",
body: insta_form,
}
);

How to retrieve PayPal REST Api access-token using node

How to get the PayPal access-token needed to leverage the REST Api by using node?
Once you have a PayPal client Id and a Client Secret you can use the following:
var request = require('request');
request.post({
uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"content-type": "application/x-www-form-urlencoded"
},
auth: {
'user': '---your cliend ID---',
'pass': '---your client secret---',
// 'sendImmediately': false
},
form: {
"grant_type": "client_credentials"
}
}, function(error, response, body) {
console.log(body);
});
The response, if successful, will be something as the following:
{
"scope":"https://api.paypal.com/v1/payments/.* ---and more URL callable with the access-token---",
"access_token":"---your access-token---",
"token_type":"Bearer",
"app_id":"APP-1234567890",
"expires_in":28800
}
Also, you can use axios, and async/await:
const axios = require('axios');
(async () => {
try {
const { data: { access_token } } = await axios({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'post',
headers: {
Accept: 'application/json',
'Accept-Language': 'en_US',
'content-type': 'application/x-www-form-urlencoded',
},
auth: {
username: client_id,
password: client_secret,
},
params: {
grant_type: 'client_credentials',
},
});
console.log('access_token: ', access_token);
} catch (e) {
console.error(e);
}
})();
Modern problems require modern solutions:
const fetch = require('node-fetch');
const authUrl = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
const clientIdAndSecret = "CLIENT_ID:SECRET_CODE";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')
fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Authorization': `Basic ${base64}`,
},
body: 'grant_type=client_credentials'
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data.access_token);
}).catch(function() {
console.log("couldn't get auth token");
});
You could use PayPal-Node-SDK to make calls to PayPal Rest APIs. It handles all the authorization and authentication for you.
Here is how I get the access_token using superagent
superagent.post('https://api.sandbox.paypal.com/v1/oauth2/token')
.set("Accept","application/json")
.set("Accept-Language","en_US")
.set("content-type","application/x-www-form-urlencoded")
.auth("Your Client Id","Your Secret")
.send({"grant_type": "client_credentials"})
.then((res) => console.log("response",res.body))

Resources