Got npm module: How to add bearer token to POST request - node.js

I recently found out that request is no longer maintained, so the best alternative I found is got. I am trying to make an external API call to a REST Server but I am unsure as to how I can add a Bearer token in the authorization header of the POST request.
This is my code:
const response = await got.post(
"https://${SERVER}/${SOME_ID}/conversations/${CONVERSATION_ID}/messages",
{
json: [
{
text: req.body.message,
type: "SystemMessage",
}
],
responseType: "json",
headers: {
token: "Bearer pXw4BpO95OOsZiDQS7mQvOjs"
}
}
);
This results in a 401 Unauthorized. I was unable to find direction to such implementation in the documentation provided by GOT. And since there are not a lot of queries regarding this package, I was unsuccessful in finding anything on Google as well. If anyone can help me out in this regard, that would be very helpful!

Are you sure that the header name is "token" ?
Usually in API, the Bearer is in a header called "Authorization"
const response = await got.post(
"https://${SERVER}/${SOME_ID}/conversations/${CONVERSATION_ID}/messages",
{
json: [
{
text: req.body.message,
type: "SystemMessage",
}
],
responseType: "json",
headers: {
"Authorization": "Bearer pXw4BpO95OOsZiDQS7mQvOjs"
}
}
);

Here is the code
npm i postman-request link for npm package
const request = require('postman-request');
request({
url: 'your url',
headers: {
'Authorization': 'Bearer 71D50F9987529'
},
rejectUnauthorized: false
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body);
}
});

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

PayPal Partner Referrals API URL

I am having trouble setting up Partner Referrals when calling the PayPal API using Node.
Every time I attempt to call the API I receive the following error:
error: "invalid_token"
error_description: "The token passed in was not found in the system"
According to the documentation the URL to call is https://api-m.sandbox.paypal.com/v2/customer/partner-referrals
Looking at the URL and the error message, I believe I am getting this error because I am using production credentials, not sandbox. However, I cannot find any documentation showing the production URL for this.
Am I correct in believing this is the sandbox URL? What is the production URL if so?
Ive followed the onboarding checklist but cant seem to make this work.
Here is my code:
getAuthToken = async () => {
const clientIdAndSecret = "mylongsecret";
const authUrl = "https://api-m.paypal.com/v1/oauth2/token";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')
const response = await fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Authorization': `Basic ${base64}`,
},
body: 'grant_type=client_credentials'
});
const data = await response.json();
return data;
}
setUpMerchant = async () => {
let authData = await this.getAuthToken();
const partnerUrl = "https://api-m.sandbox.paypal.com/v2/customer/partner-referrals";
let data = {
"operations": [
{
"operation": "API_INTEGRATION",
"api_integration_preference": {
"rest_api_integration": {
"integration_method": "PAYPAL",
"integration_type": "THIRD_PARTY",
"third_party_details": {
"features": [
"PAYMENT",
"REFUND"
]
}
}
}
}
],
"products": [
"EXPRESS_CHECKOUT"
],
"legal_consents": [
{
"type": "SHARE_DATA_CONSENT",
"granted": true
}
]
};
const request = await fetch(partnerUrl, {
method: 'POST',
headers: {
'Authorization': 'Bearer '+authData.access_token,
'Content-Type': 'application/json',
'data': data,
},
});
const partnerData = await request.json();
return partnerData;
}
Edit: I discovered the issue was I was running a GET request instead of a POST. The accepted answer is the correct URL
According to the documentation the URL to call is https://api-m.sandbox.paypal.com/v2/customer/partner-referrals
The production URL does not have sandbox. in the domain.

How to use axios.post method for a cURL command? (Or fix status code: 415)

We need to run the axios.post equivalent for following cURL command in nodeJS:
curl -H "Authorization: Basic ZjM4Zj...Y0MzE=" -d grant_type=refresh_token -d refresh_token=NgAagA...NUm_SHo https://accounts.spotify.com/api/token
My Approach:
axios.post("https://accounts.spotify.com/api/token", {
grant_type: 'refresh_token',
refresh_token: 'NgAagA...NUm_SHo',
header: {
Authorization: 'Basic ZjM4Zj...Y0MzE=',
}
}).then((resAxios) => {
console.log(resAxios.data)
spotifyResult = resAxios.data;
}).catch((error) => {
console.error(error)
})
Above code returns the following error in reponse:
statusCode: 415,
statusMessage: 'Unsupported Media Type'
Format:
refresh_token should be application/x-www-form-urlencoded
Authorization: Basic <base64 encoded client_id:client_secret>
Refer the 'Authorization Code Flow' for the cURL command, here:
https://developer.spotify.com/documentation/general/guides/authorization-guide/
Feel free to provide with any other variant, i.e., instead of using axios. I preferred it, since it parses the fetched data as well. Please provide with the code to parse it with, if so. I'm a 'beginner' beginner.
Thanks to all the folks: Manuel Spigolon, zx01, Mark Stroebel, Łukasz Szewczak, ponury-kostek, Jakub Luczak, Gerardo Gonzalez :)
I tried this answer on this link, as provided by #zx01 in the comments to the question.
Final code, tailored to the needs:
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "refresh_token",
//grant_type: "client_credentials", //This works as well.
refresh_token: 'AQAw95rH0...CnWBE'
},
headers: {
Authorization:'Basic MWQ4Z...dhYmU=',
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
}).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.log(error);
});
However, the following syntax doesn't seems to work.
It again returns with status code 415: Unsupported Media Type.
axios.post("https://accounts.spotify.com/api/token", null, {
params: {
grant_type: "refresh_token",
//grant_type: "client_credentials", //This doesn't work either.
refresh_token: 'AQAw95rH0...CnWBE'
},
headers: {
Authorization:'Basic MWQ4Z...dhYmU=',
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
}).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.log(error);
});
It'd be dope if somebody could fix the above code, and reason as to why we're getting that error.
Also notice there is a quomma ',', next to the closing curly braces that packs the 'headers' property.

Discord Profil Picture Update from ElectronJS using request PATCH

I'm trying to code an application into Electron JS to allow the person to change their profile picture at the same time on several applications.
For this I use the APIs of each platform.
For Twitter it works correctly, but I block at the level of Discord.
I can make a GET request on the profile, but I can't do a : PATCH/users/#me
https://discordapp.com/developers/docs/resources/user#modify-current-user
I do not know if it's the token that does not offer enough power, because I only asked for Identity as permission on my application.
I tried to pass JSON between true and false,
to add a content type, but I still have the same answer: {code: 0, message: '401: Unauthorized'}
function postDiscord(image) {
const imageDataURI = require('image-data-uri')
let {token} = store.get('discordToken') //get stored token
imageDataURI.encodeFromFile(image)
.then(res => {
request({
method: 'PATCH',
url: 'https://discordapp.com/api/v6/users/#me',
headers: {
'Authorization': 'Bearer '+token,
'User-Agent': 'someBot (site, v0.1)'
},
body: {
'avatar': res
},
json: true
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body)
}
}
);
})
}
{code: 0, message: '401: Unauthorized'}
Refering to Discord :https://github.com/discordapp/discord-api-docs/issues/1057
Cannot upload new pics with Oauth :/

Request must have at least one newMediaItem - Google Photos API

I'm trying to create media item using Google Photos API. Endpoint is documented here. If I copy and paste my payload to an API explorer which can be found in documentation, I get success:
Request inputed to an API Explorer and Successful response.
If I do the same in my node js program, I'm getting an error.
This is what I do:
const accessToken = "MyAccessToken";
payload = {
"newMediaItems": [
{
"description": "picture",
"simpleMediaItem": {
"uploadToken": "CAIS+QIASsyg4OQLX2Ao5hy6I734/b01mjk3Mqpom6DQ24iv7ZfAYLiXAy0WpOXCWJBNHrmBs6FE+a9Axu5CML+Ryu4VGawyf4skxM763mzC5GcjMY4rS/r6IwOekBIoE/aMJLJpRr1gW8jdhVJM89+kioTx9d+shyYeQDbVI8ezb1lXGp6irc9hZl7QA6xd+msXzbLD5nb+wc5CA6du95tP3buh5R5N/Knn+NwByebdEPCusl+X3p7DZ6ha72kLthUqdvwFsp8dpnGbNQBq8AFPVNHXB4C543iq+dYiRFYtICCxO8xi2cpONVT54Jl6l9rGh3Vnidwj5IwkbsXkyiN96HfRb9XLh0rCBw4ydV6Y9+C+OmTAqlQwIKy50I/ykHyzggroeJSbgphiQwFR2EbHwAeSKdsdIB03ItnunHtf3F2LRIitDRGI1n4VUEYE1dYjrrjR791ao24Dp8J3Hg8IRb8E3vFTeYMWyOk4mh/zQGInfNBnRY2ruHH0JA"
}
}
]
};
const response = await fetch('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`
},
payload: JSON.stringify(payload)
});
const json = await response.json();
console.log(json);
And getting this response:
{ error:
{ code: 400,
message: 'Request must have at least one newMediaItem.',
status: 'INVALID_ARGUMENT' } }
What could go wrong here?
Any help is appreciated, thank you.
It looks like you are setting the JSON payload in the wrong parameter in your call to fetch. It should be set in the parameter body (and not in payload). The JSON itself looks okay.
This snippet should work:
const response = await fetch('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`
},
body: JSON.stringify(payload)
});
Source: node-fetch 'Post with JSON' example

Resources