0
const got = require('got');   
 var config = {
      url: '/authorization/tokenrequest',
      body: data,
      // method: 'post',
      headers: {
        'Content-Type': 'application/json', 
      }
    }

module.exports.hello = async() => {
  const response = await got.post(config).then(ok => {
    console.log(ok.body);
    var parsedJson = JSON.parse(ok.body);
    if(parsedJson.Value.Success){
      var token = 'Bearer ' + parsedJson.Value.AuthenticationToken;
      
      var data = JSON.stringify({"userid","test"});
      var configs = {
        method: 'post',
        url: '/user/userprofile',
        headers: {
          'Authorization': 'Bearer oYi1hP9p20LUi8DIERHhITGXEsVNkEweEshN6VMNsssCTBy8iYBxbcH3GJDyNJ9KILejscff5kQrM3V9uTecgaS1cu90xXmcb4L0NiVY4gHvotbazG8ARDZ5vE29bkQhaxaZunqZyb6mwLtGVz3IpYJxAg7hR9zi6x3tWE3Ir56wiFoXnZfgUgYJKdn8FMeC+Yyj6a7B19/MDqTs85rqN1V4RflNEy+tZr2c+lCicMarQdjMLOs2GISEFuouXDRdl4J8cYWRHIE/aVNwkhB5g4sHMlYdO+Lcva6bmowl8WrPUoCOzgxEzV9PzGHmjKY1sgn5HLv85MYySx1Y6XliKZ/lBW9N4L75iwm87rFbjhVJxzSEqRQEt9c6e71fc5fxkv01ITnmdnD57eFkZzLqV2A1NbUBId8qb2dh1rfjq7PD8ohFtMFSOcB4tuHbUx8k8NQn+ws/MW/hItOSnqF2/pj8UR/Sf8txm3ncAHr2GLaoYbfRg++GrVusk/wFhjzmm8jzbJR0acJN01XLxBX7zhO8xzQCKgjXruonnSGF821Vl1F328GvwMLDpwKOTbi/zlPZA2G7d++mkGaiW6hH2/n3TKSXurVcnpAeVEvEaCAvLoMZvucNIAkSuD9mhEOq', 
          'Content-Type': 'application/json',
        },
        data : data
      };

      console.log(configs);
      const userResponse = got.post(configs).then(ok => {
      console.log(ok.userResponse);
      var userResponseJson = JSON.parse(ok.userResponse);
      console.log(userResponseJson);
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }).catch(reject);
}

出现以下错误 HTTPError: Response code 500 (Internal Server Error) at Request.request.once (\node_modules\got\dist\source\as-promise\index.js:117:42) at process._tickCallback (internal/process/ next_tick.js:68:7)

获取令牌然后在节点 js 的另一个端点中使用它的最佳方法。

4

1 回答 1

0

你可以写这样的东西。您可以从 ApiInstance 类中获取实例。您可以访问异步和承诺结构化的 getUserProfile 函数。您并不总是需要使用此结构运行令牌功能。您还可以为其添加令牌过期日期检查。这种结构还可以实现封装。我希望,你的意思是这样的,它会有所帮助。

const apiInstance = new ApiInstance();

module.exports.hello = async () => {
  const data = '';
  let userProfile;

  try {
    userProfile = await apiInstance.getUserProfile(data);
  } catch (error) {
    console.error(error);
  }

  if (userProfile) {
    console.info('User Profile:', userProfile);
  } else {
    console.info('User profile not found!');
  }
}

function ApiInstance() {
  const got = require('got');
  let token = null;

  const getToken = async () => {

    if (token) {
      return token;
    } else {
      const data = '';
      const config = {
        url: '/authorization/tokenrequest',
        body: data,
        headers: {
          'Content-Type': 'application/json',
        }
      }

      return got.post(config)
        .then(response => {
          return JSON.parse(response.body).Value.AuthenticationToken;
        })
        .catch(error => {
          console.error(error);
          return null;
        })
    }
  }

  this.getUserProfile = async (data) => {
    token = await getToken();
    const config = {
      method: 'post',
      url: '/user/userprofile',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      data: data
    };

    return got.post(config)
      .then(response => response.userResponse)
      .catch(error => {
        console.error(error);
        return null;
      })
  }
}
于 2022-01-20T11:13:14.713 回答