节点中的单个脚本从某个 xyz oauth2 /token 端点获取 authToken 并调用以下 api。我在下面编写了类似的代码

a single script in node to get authToken from some xyz oath2 /token end point and call the following api. I have coded something like this below

// getToken.mjs

import axios from 'axios'; 
import qs from 'qs';
var data = qs.stringify({
  'client_id': 'xxxx-xxx',
  'client_secret':  'xxxx-xxx',
  'scope': 'https://graph.microsoft.com/.default',
  'grant_type': 'client_credentials' 
});
const config = {
  method: 'get',
  url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
  headers: { 
    'Content-Type': 'application/x-www-form-urlencoded',   },
  data : data
};

export let accessToken = axios(config)
.then(function (response) {
  console.log((response.data.access_token));
})
.catch(function (error) {
  console.log(error);
});

------------在第二个脚本中调用API -----

//得到response.js

import axios from "axios";
import { accessToken } from "./getToken.mjs";
const config = {
  method: 'get',
  url: 'https://graph.microsoft.com/v1.0/me/',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': `Bearer ${accessToken}`,
  }
};


export let data000 = axios(config).then(function (response) {
  console.log(JSON.stringify(response.data));
}).catch(function (error) {
  console.log(error);
});


console.log(data000);

在执行 > node response.js ... returns 401,客户端密码和 id 是正确的。但是,我觉得 accessToken 没有被导入,因此出现了错误。我该如何解决这个问题?

尝试使用POST方法得到accessToken

const config = {
  method: 'post',
  url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
  headers: { 
    'Content-Type': 'application/x-www-form-urlencoded',   },
  data : data
};