Axios-动态标题不起作用。当我动态设置变量时,为什么我的代码不起作用,而当我对其进行硬编码时,为什么我的代码却不起作用?

时间:2019-12-03 22:35:00

标签: javascript authentication axios

我似乎无法弄清楚如何使我的第二个http帖子“排队回叫”。看来问题是特定于我如何设置标题的。标头= my_headers。当我对它进行硬编码时,它会起作用,但是当我尝试动态调用它时,它就不会起作用。任何帮助将不胜感激。谢谢!

const axios = require('axios');
const queuecallback = require('axios');

 var my_token;
 var my_formated_token;
 var my_headers;
 var myJSON;
   function connectToAgentHandler(agent) {
        axios({
          method: 'post',
          url: 'https://myapi.com/AuthorizationServer/Token',
          data: {
        username: 'myusername',
        password: 'mypassword',
        grant_type: 'password'
            },
        headers: {'Authorization': 'basic 123456789Aghtiaqq111kkksksksk111'}
          }
        )
        .then((result) => {
           my_token = result.data.access_token;
          console.log("Token:", my_token);
          my_formated_token = 'bearer ' + my_token;
          console.log("Formated Token:", my_formated_token); 

          var my_headers = "{'Authorization': '" + my_formated_token + "'}";
          console.log("My Headers:", my_headers);
                  });  

 //lets execute the callback from an agent
  queuecallback({
          method: 'post',
          url: 'https://myapi.com/go',
          data: {
        phoneNumber: '1111111111',
        skill: '12345'
            },
       headers: my_headers              
  }
        )
        .then((result) => {
                  console.log("your contactId is:", result.data.contactId);
                  }); 
      }  

});

1 个答案:

答案 0 :(得分:0)

不需要两个axios:

const axios = require('axios');
const queuecallback = require('axios');

您的问题是您在第一次调用中设置了标头

var my_headers = "{'Authorization': '" + my_formated_token + "'}";

axios是一个异步函数,因此在第一次queuecallback调用(尚未完成)之后直接调用axios。您可以使用异步功能来“等待”第一个调用的结束:

const axios = require('axios');

async function connectToAgentHandler(agent) {
  try {
    let result = await axios({
      method: 'post',
      url: 'https://myapi.com/AuthorizationServer/Token',
      data: {
        username: 'myusername',
        password: 'mypassword',
        grant_type: 'password'
      },
      headers: {
        'Authorization': 'basic 123456789Aghtiaqq111kkksksksk111'
      }
    });

    const token = `bearer ${result.data.access_token}`;

    const headers = {
      'Authorization': token
    };

    result = axios({
      method: 'post',
      url: 'https://myapi.com/go',
      data: {
        phoneNumber: '1111111111',
        skill: '12345'
      },
      headers
    });

    console.log("your contactId is:", result.data.contactId);
  } catch (err) {
    // process error
  }
};