【问题标题】:How to return the token as a value? Node js如何将令牌作为值返回?节点js
【发布时间】:2022-01-23 22:34:33
【问题描述】:

我该如何解决这个问题?我发出了一个post请求来获取token,但是当我返回它时,它返回为未定义,但是当我打印它时,它显示token OK。

function getToken() {

  // The req.query object has the query params that
  // were sent to this route. We want the `code` param
  axios({
    // make a POST request
    method: "post",
    // to the Github authentication API, with the client ID, client secret
    // and request token
    url: ` https://backstage.taboola.com/backstage/oauth/token?client_id=${clientID}&client_secret=${clientSecret}&grant_type=client_credentials`,
    // Set the content type header, so that we get the response in JSOn
    headers: {
      accept: "application/json",
    },
  }).then((response) => {
    // Once we get the response, extract the access token from
    // the response body
    accessToken = response.data.access_token;
    //console.log(accessToken);
    return(accessToken);
  });
};

【问题讨论】:

标签: javascript node.js token


【解决方案1】:

你可以这样做

async function getToken() {

  // The req.query object has the query params that
  // were sent to this route. We want the `code` param
  const response = await axios({
    // make a POST request
    method: "post",
    // to the Github authentication API, with the client ID, client secret
    // and request token
    url: ` https://backstage.taboola.com/backstage/oauth/token?client_id=${clientID}&client_secret=${clientSecret}&grant_type=client_credentials`,
    // Set the content type header, so that we get the response in JSOn
    headers: {
      accept: "application/json",
    },
  });
  return response.data.access_token
};

const token = await getToken();
console.log(token)
// more https://www.w3schools.com/js/js_promise.asp

【讨论】:

  • 不起作用,它仍然返回“未定义”,但是当我在返回之前打印令牌时,它仍然显示令牌正确
  • 你的意思是 console.log(response.data.access_token) 有效吗?
  • @Anees ure 使用了错误的承诺 :) 你甚至没有从 getToken() 函数(响应变量)返回任何东西,更不用说你已经从 axios 中删除了原始承诺;应该更像return await axios({}).then(...) 或简单的return axios().then(),即使没有等待,因为它本身就是一个承诺,你在await getToken(); 之后等待它
猜你喜欢
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 2017-03-20
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
相关资源
最近更新 更多