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










0















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?










share|improve this question


























    0















    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?










    share|improve this question
























      0












      0








      0








      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?










      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 4 at 19:31









      OrdinaryHumanOrdinaryHuman

      179115




      179115






















          2 Answers
          2






          active

          oldest

          votes


















          0














          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.






          share|improve this answer























          • Changing to application/json has no effect, nor does using qs.stringify with form-encoded. any other ideas?

            – OrdinaryHuman
            Mar 4 at 20:05


















          0














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





          share|improve this answer
























            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
            );



            );













            draft saved

            draft discarded


















            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









            0














            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.






            share|improve this answer























            • Changing to application/json has no effect, nor does using qs.stringify with form-encoded. any other ideas?

              – OrdinaryHuman
              Mar 4 at 20:05















            0














            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.






            share|improve this answer























            • Changing to application/json has no effect, nor does using qs.stringify with form-encoded. any other ideas?

              – OrdinaryHuman
              Mar 4 at 20:05













            0












            0








            0







            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.






            share|improve this answer













            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 4 at 19:46









            QuentinQuentin

            652k728851049




            652k728851049












            • 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
















            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













            0














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





            share|improve this answer





























              0














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





              share|improve this answer



























                0












                0








                0







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





                share|improve this answer















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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 2 days ago

























                answered 2 days ago









                OrdinaryHumanOrdinaryHuman

                179115




                179115



























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme