Oauth 2.0 request with Axios failing2019 Community Moderator ElectionJavaScript post request like a form submitHow to manage a redirect request after a jQuery Ajax callAbort Ajax requests using jQueryHow is an HTTP POST request made in node.js?Sending OAuth access token in Jquery Ajax requestCant seem to make cookie authenticated requests using UnirestCan't parse JSON after sending it via Ajax requestBasic HTTP authorization headeraxios patch not working in chromeHow to overcome CORS issue and get a response from a server which runs at a different origin than the react app
Propulsion Systems
Is there a math expression equivalent to the conditional ternary operator?
Interpretation of linear regression interaction term plot
Too soon for a plot twist?
Precision notation for voltmeters
Use Mercury as quenching liquid for swords?
How to recover against Snake as a heavyweight character?
How do you make a gun that shoots melee weapons and/or swords?
Why isn't P and P/poly trivially the same?
A running toilet that stops itself
How to educate team mate to take screenshots for bugs with out unwanted stuff
Create chunks from an array
Short SF story. Females use stingers to implant eggs in yearfathers
Is there a logarithm base for which the logarithm becomes an identity function?
What is the purpose of a disclaimer like "this is not legal advice"?
Should I apply for my boss's promotion?
Help! My Character is too much for her story!
Is it appropriate to ask a former professor to order a library book for me through ILL?
What does *dead* mean in *What do you mean, dead?*?
Paper published similar to PhD thesis
What exactly is the meaning of "fine wine"?
How to make sure I'm assertive enough in contact with subordinates?
Short story about cities being connected by a conveyor belt
What is the oldest European royal house?
Oauth 2.0 request with Axios failing
2019 Community Moderator ElectionJavaScript post request like a form submitHow to manage a redirect request after a jQuery Ajax callAbort Ajax requests using jQueryHow is an HTTP POST request made in node.js?Sending OAuth access token in Jquery Ajax requestCant seem to make cookie authenticated requests using UnirestCan't parse JSON after sending it via Ajax requestBasic HTTP authorization headeraxios patch not working in chromeHow to overcome CORS issue and get a response from a server which runs at a different origin than the react app
I'm able to interface with the Yahoo Fantasy API using Oauth 2.0 in PHP, but when I try to convert my code into JavaScript using Axios HTTP request library, I get no response. What am I doing wrong?
First, here's the working, valid PHP version:
function refreshAuthorizationToken($token)
$consumer_key = "consumerKeyGoesHere";
$consumer_secret = "myConsumerSecretGoesHere";
$auth_header = base64_encode($consumer_key . ":" . $consumer_secret);
$auth_endpoint = "https://api.login.yahoo.com/oauth2/get_token";
$ch = curl_init();
$post_values = [
"redirect_uri" => "oob",
"grant_type" => "refresh_token",
"refresh_token" => $token
];
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $auth_endpoint,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $auth_header,
'Access-Control-Request-Headers: authorization',
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'),
CURLOPT_POSTFIELDS => http_build_query($post_values)
));
$answer = curl_exec($ch);
$token = json_decode($answer);
if (!isset($access_token))
return "Error: access token not set."
else
return $token;
Now here's the JavaScript code that's not working:
const consumerKey = `consumerKeyGoesHere`;
const consumerSecret = `consumerSecretGoesHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
async function refreshAuthorizationToken(token)
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
let response;
try
response = await axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Access-Control-Request-Headers': 'authorization',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data:
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
,
timeout: 1000,
);
if (response.data) writeToFile(response.data, authFile, 'w');
return JSON.parse(response.data);
catch (error)
console.error(`Error in refreshAuthorizationToken: $error`);
I've tried params
instead of data
but no matter what this request just dies with no response no matter how I try to catch errors (tried a few different permutations).
I thought maybe this was an HTTPS issue, but even if I create an HTTPS server with a self-signed certificate the request still dies silently.
Any idea how to fix this? Or examples of a properly formed OAuth 2.0 client refresh token request using Axios/Node?
javascript node.js axios
add a comment |
I'm able to interface with the Yahoo Fantasy API using Oauth 2.0 in PHP, but when I try to convert my code into JavaScript using Axios HTTP request library, I get no response. What am I doing wrong?
First, here's the working, valid PHP version:
function refreshAuthorizationToken($token)
$consumer_key = "consumerKeyGoesHere";
$consumer_secret = "myConsumerSecretGoesHere";
$auth_header = base64_encode($consumer_key . ":" . $consumer_secret);
$auth_endpoint = "https://api.login.yahoo.com/oauth2/get_token";
$ch = curl_init();
$post_values = [
"redirect_uri" => "oob",
"grant_type" => "refresh_token",
"refresh_token" => $token
];
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $auth_endpoint,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $auth_header,
'Access-Control-Request-Headers: authorization',
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'),
CURLOPT_POSTFIELDS => http_build_query($post_values)
));
$answer = curl_exec($ch);
$token = json_decode($answer);
if (!isset($access_token))
return "Error: access token not set."
else
return $token;
Now here's the JavaScript code that's not working:
const consumerKey = `consumerKeyGoesHere`;
const consumerSecret = `consumerSecretGoesHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
async function refreshAuthorizationToken(token)
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
let response;
try
response = await axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Access-Control-Request-Headers': 'authorization',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data:
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
,
timeout: 1000,
);
if (response.data) writeToFile(response.data, authFile, 'w');
return JSON.parse(response.data);
catch (error)
console.error(`Error in refreshAuthorizationToken: $error`);
I've tried params
instead of data
but no matter what this request just dies with no response no matter how I try to catch errors (tried a few different permutations).
I thought maybe this was an HTTPS issue, but even if I create an HTTPS server with a self-signed certificate the request still dies silently.
Any idea how to fix this? Or examples of a properly formed OAuth 2.0 client refresh token request using Axios/Node?
javascript node.js axios
add a comment |
I'm able to interface with the Yahoo Fantasy API using Oauth 2.0 in PHP, but when I try to convert my code into JavaScript using Axios HTTP request library, I get no response. What am I doing wrong?
First, here's the working, valid PHP version:
function refreshAuthorizationToken($token)
$consumer_key = "consumerKeyGoesHere";
$consumer_secret = "myConsumerSecretGoesHere";
$auth_header = base64_encode($consumer_key . ":" . $consumer_secret);
$auth_endpoint = "https://api.login.yahoo.com/oauth2/get_token";
$ch = curl_init();
$post_values = [
"redirect_uri" => "oob",
"grant_type" => "refresh_token",
"refresh_token" => $token
];
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $auth_endpoint,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $auth_header,
'Access-Control-Request-Headers: authorization',
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'),
CURLOPT_POSTFIELDS => http_build_query($post_values)
));
$answer = curl_exec($ch);
$token = json_decode($answer);
if (!isset($access_token))
return "Error: access token not set."
else
return $token;
Now here's the JavaScript code that's not working:
const consumerKey = `consumerKeyGoesHere`;
const consumerSecret = `consumerSecretGoesHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
async function refreshAuthorizationToken(token)
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
let response;
try
response = await axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Access-Control-Request-Headers': 'authorization',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data:
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
,
timeout: 1000,
);
if (response.data) writeToFile(response.data, authFile, 'w');
return JSON.parse(response.data);
catch (error)
console.error(`Error in refreshAuthorizationToken: $error`);
I've tried params
instead of data
but no matter what this request just dies with no response no matter how I try to catch errors (tried a few different permutations).
I thought maybe this was an HTTPS issue, but even if I create an HTTPS server with a self-signed certificate the request still dies silently.
Any idea how to fix this? Or examples of a properly formed OAuth 2.0 client refresh token request using Axios/Node?
javascript node.js axios
I'm able to interface with the Yahoo Fantasy API using Oauth 2.0 in PHP, but when I try to convert my code into JavaScript using Axios HTTP request library, I get no response. What am I doing wrong?
First, here's the working, valid PHP version:
function refreshAuthorizationToken($token)
$consumer_key = "consumerKeyGoesHere";
$consumer_secret = "myConsumerSecretGoesHere";
$auth_header = base64_encode($consumer_key . ":" . $consumer_secret);
$auth_endpoint = "https://api.login.yahoo.com/oauth2/get_token";
$ch = curl_init();
$post_values = [
"redirect_uri" => "oob",
"grant_type" => "refresh_token",
"refresh_token" => $token
];
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $auth_endpoint,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . $auth_header,
'Access-Control-Request-Headers: authorization',
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'),
CURLOPT_POSTFIELDS => http_build_query($post_values)
));
$answer = curl_exec($ch);
$token = json_decode($answer);
if (!isset($access_token))
return "Error: access token not set."
else
return $token;
Now here's the JavaScript code that's not working:
const consumerKey = `consumerKeyGoesHere`;
const consumerSecret = `consumerSecretGoesHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
async function refreshAuthorizationToken(token)
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
let response;
try
response = await axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Access-Control-Request-Headers': 'authorization',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data:
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
,
timeout: 1000,
);
if (response.data) writeToFile(response.data, authFile, 'w');
return JSON.parse(response.data);
catch (error)
console.error(`Error in refreshAuthorizationToken: $error`);
I've tried params
instead of data
but no matter what this request just dies with no response no matter how I try to catch errors (tried a few different permutations).
I thought maybe this was an HTTPS issue, but even if I create an HTTPS server with a self-signed certificate the request still dies silently.
Any idea how to fix this? Or examples of a properly formed OAuth 2.0 client refresh token request using Axios/Node?
javascript node.js axios
javascript node.js axios
asked Mar 4 at 19:31
OrdinaryHumanOrdinaryHuman
179115
179115
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
See the documentation for axios:
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
You are setting a Content-Type
header which claims you are sending application/x-www-form-urlencoded
data, but you haven't done any of the things that the documentation suggests to generate data in that format.
Aside:
'Access-Control-Request-Headers': 'authorization',
That's a response header, it makes no sense to include it on the request.
Changing toapplication/json
has no effect, nor does usingqs.stringify
with form-encoded. any other ideas?
– OrdinaryHuman
Mar 4 at 20:05
add a comment |
There were two problems -- one, as Quentin pointed out below, I needed to stringify the data JSON if I'm going to use application/x-www-form-urlencoded
(which the Yahoo API requires).
The second problem was my promise handling. refreshAuthorizationToken
should not be async nor use await, it should just return axios -- it's the calling function that should use async/await.
The working code:
const qs = require('qs');
const fs = require('fs');
const axios = require('axios');
const consumerKey = `myConsumerKeyHere`;
const consumerSecret = `myConsumerSecretHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
function writeToFile(data, file, flag)
if (flag === null) flag = `a`;
fs.writeFile(file, data, flag: flag, (err) =>
if (err)
console.error(`Error in writing to $file: $err`);
);
function refreshAuthorizationToken(token)
return axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data: qs.stringify(
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
),
timeout: 1000,
).catch((error) =>
console.log(`Some kind of horrible error in refreshAuthorizationToken: $error`);
);
async function reload()
const returnVal = await refreshAuthorizationToken(credentials.refresh_token);
if (returnVal)
if (returnVal.data && returnVal.data.access_token)
writeToFile(JSON.stringify(returnVal.data), authFile, 'w');
reload();
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54990313%2foauth-2-0-request-with-axios-failing%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
See the documentation for axios:
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
You are setting a Content-Type
header which claims you are sending application/x-www-form-urlencoded
data, but you haven't done any of the things that the documentation suggests to generate data in that format.
Aside:
'Access-Control-Request-Headers': 'authorization',
That's a response header, it makes no sense to include it on the request.
Changing toapplication/json
has no effect, nor does usingqs.stringify
with form-encoded. any other ideas?
– OrdinaryHuman
Mar 4 at 20:05
add a comment |
See the documentation for axios:
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
You are setting a Content-Type
header which claims you are sending application/x-www-form-urlencoded
data, but you haven't done any of the things that the documentation suggests to generate data in that format.
Aside:
'Access-Control-Request-Headers': 'authorization',
That's a response header, it makes no sense to include it on the request.
Changing toapplication/json
has no effect, nor does usingqs.stringify
with form-encoded. any other ideas?
– OrdinaryHuman
Mar 4 at 20:05
add a comment |
See the documentation for axios:
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
You are setting a Content-Type
header which claims you are sending application/x-www-form-urlencoded
data, but you haven't done any of the things that the documentation suggests to generate data in that format.
Aside:
'Access-Control-Request-Headers': 'authorization',
That's a response header, it makes no sense to include it on the request.
See the documentation for axios:
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
You are setting a Content-Type
header which claims you are sending application/x-www-form-urlencoded
data, but you haven't done any of the things that the documentation suggests to generate data in that format.
Aside:
'Access-Control-Request-Headers': 'authorization',
That's a response header, it makes no sense to include it on the request.
answered Mar 4 at 19:46
QuentinQuentin
652k728851049
652k728851049
Changing toapplication/json
has no effect, nor does usingqs.stringify
with form-encoded. any other ideas?
– OrdinaryHuman
Mar 4 at 20:05
add a comment |
Changing toapplication/json
has no effect, nor does usingqs.stringify
with form-encoded. any other ideas?
– OrdinaryHuman
Mar 4 at 20:05
Changing to
application/json
has no effect, nor does using qs.stringify
with form-encoded. any other ideas?– OrdinaryHuman
Mar 4 at 20:05
Changing to
application/json
has no effect, nor does using qs.stringify
with form-encoded. any other ideas?– OrdinaryHuman
Mar 4 at 20:05
add a comment |
There were two problems -- one, as Quentin pointed out below, I needed to stringify the data JSON if I'm going to use application/x-www-form-urlencoded
(which the Yahoo API requires).
The second problem was my promise handling. refreshAuthorizationToken
should not be async nor use await, it should just return axios -- it's the calling function that should use async/await.
The working code:
const qs = require('qs');
const fs = require('fs');
const axios = require('axios');
const consumerKey = `myConsumerKeyHere`;
const consumerSecret = `myConsumerSecretHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
function writeToFile(data, file, flag)
if (flag === null) flag = `a`;
fs.writeFile(file, data, flag: flag, (err) =>
if (err)
console.error(`Error in writing to $file: $err`);
);
function refreshAuthorizationToken(token)
return axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data: qs.stringify(
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
),
timeout: 1000,
).catch((error) =>
console.log(`Some kind of horrible error in refreshAuthorizationToken: $error`);
);
async function reload()
const returnVal = await refreshAuthorizationToken(credentials.refresh_token);
if (returnVal)
if (returnVal.data && returnVal.data.access_token)
writeToFile(JSON.stringify(returnVal.data), authFile, 'w');
reload();
add a comment |
There were two problems -- one, as Quentin pointed out below, I needed to stringify the data JSON if I'm going to use application/x-www-form-urlencoded
(which the Yahoo API requires).
The second problem was my promise handling. refreshAuthorizationToken
should not be async nor use await, it should just return axios -- it's the calling function that should use async/await.
The working code:
const qs = require('qs');
const fs = require('fs');
const axios = require('axios');
const consumerKey = `myConsumerKeyHere`;
const consumerSecret = `myConsumerSecretHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
function writeToFile(data, file, flag)
if (flag === null) flag = `a`;
fs.writeFile(file, data, flag: flag, (err) =>
if (err)
console.error(`Error in writing to $file: $err`);
);
function refreshAuthorizationToken(token)
return axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data: qs.stringify(
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
),
timeout: 1000,
).catch((error) =>
console.log(`Some kind of horrible error in refreshAuthorizationToken: $error`);
);
async function reload()
const returnVal = await refreshAuthorizationToken(credentials.refresh_token);
if (returnVal)
if (returnVal.data && returnVal.data.access_token)
writeToFile(JSON.stringify(returnVal.data), authFile, 'w');
reload();
add a comment |
There were two problems -- one, as Quentin pointed out below, I needed to stringify the data JSON if I'm going to use application/x-www-form-urlencoded
(which the Yahoo API requires).
The second problem was my promise handling. refreshAuthorizationToken
should not be async nor use await, it should just return axios -- it's the calling function that should use async/await.
The working code:
const qs = require('qs');
const fs = require('fs');
const axios = require('axios');
const consumerKey = `myConsumerKeyHere`;
const consumerSecret = `myConsumerSecretHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
function writeToFile(data, file, flag)
if (flag === null) flag = `a`;
fs.writeFile(file, data, flag: flag, (err) =>
if (err)
console.error(`Error in writing to $file: $err`);
);
function refreshAuthorizationToken(token)
return axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data: qs.stringify(
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
),
timeout: 1000,
).catch((error) =>
console.log(`Some kind of horrible error in refreshAuthorizationToken: $error`);
);
async function reload()
const returnVal = await refreshAuthorizationToken(credentials.refresh_token);
if (returnVal)
if (returnVal.data && returnVal.data.access_token)
writeToFile(JSON.stringify(returnVal.data), authFile, 'w');
reload();
There were two problems -- one, as Quentin pointed out below, I needed to stringify the data JSON if I'm going to use application/x-www-form-urlencoded
(which the Yahoo API requires).
The second problem was my promise handling. refreshAuthorizationToken
should not be async nor use await, it should just return axios -- it's the calling function that should use async/await.
The working code:
const qs = require('qs');
const fs = require('fs');
const axios = require('axios');
const consumerKey = `myConsumerKeyHere`;
const consumerSecret = `myConsumerSecretHere`;
const authHeader = Buffer.from(`$consumerKey:$consumerSecret`, `binary`).toString(`base64`);
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
function writeToFile(data, file, flag)
if (flag === null) flag = `a`;
fs.writeFile(file, data, flag: flag, (err) =>
if (err)
console.error(`Error in writing to $file: $err`);
);
function refreshAuthorizationToken(token)
return axios(
url: authEndpoint,
method: 'post',
headers:
'Authorization': `Basic $authHeader`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
,
data: qs.stringify(
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
),
timeout: 1000,
).catch((error) =>
console.log(`Some kind of horrible error in refreshAuthorizationToken: $error`);
);
async function reload()
const returnVal = await refreshAuthorizationToken(credentials.refresh_token);
if (returnVal)
if (returnVal.data && returnVal.data.access_token)
writeToFile(JSON.stringify(returnVal.data), authFile, 'w');
reload();
edited 2 days ago
answered 2 days ago
OrdinaryHumanOrdinaryHuman
179115
179115
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54990313%2foauth-2-0-request-with-axios-failing%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown