You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure APIM代理API问题:NodeJS请求返回空Token

问题:Axios调用Azure APIM代理API返回空Token

背景

环境禁止直接调用https://login.microsoftonline.com,因此在Azure APIM中创建了代理API,入站策略如下:

Policy Type: Inbound
Get & set-variables from header (scope, client id, secret & grant type)
send-request to https://login.microsoftonline.com
set-method to POST
set-header Content-Type to x-www-form-urlencoded
set-body to return scope, client id, secret and grant type
get the response body
get the access token
set the token in a new body (liquid template)
set the body in return-response (convert body to string)

测试情况

  • APIM内部测试、Postman调用该代理API均正常,响应示例:
{
    "status": "ok",
    "token": "Bearer ASODIA@#$)(*ASDJASODNADSAOSDJ....PROPER TOKEN"
}
  • 使用NodeJS的Axios调用时,返回200 OK但Token为空,响应示例:
{
    "status": "ok",
    "token": "Bearer "
}

调用代码

使用的NodeJS Axios代码如下:

router.get("/test", async (req, res) => {
  let config = {
    headers: {
      client_id: process.env["BID"],
      client_secret: process.env["BSEC"],
      scope: process.env["BSCOPE"],
    },
  };

  let data = {
    "Content-Type": "application/json",
  };

  const apimUrl = "https://gateway-test.hapi.hmgroup.com/hapi-utils-auth/token";
  axios
    .get(apimUrl, data, config)
    .then((response) => {
      console.log(response.data);
      res.send(response.data);
    })
    .catch((error) => {
      console.log(error);
    });
});

原因分析

  1. 缺失关键请求头:APIM策略明确要求从请求头获取grant type变量,但你当前的Axios代码中完全没有传入这个头,Postman测试时应该携带了该参数,所以能正常拿到Token。
  2. Axios GET请求调用格式错误:Axios的get方法参数格式为axios.get(url[, config]),你把data作为第二个参数传入,这会被当作配置的一部分而非请求体,虽然GET请求本身不依赖请求体,但这种错误写法可能导致配置解析异常,同时你在data里设置Content-Type的方式完全不符合Axios的配置规范。

解决方案

  1. 补全缺失的请求头:在config.headers中添加grant_type(通常为client_credentials,可根据实际认证类型调整)。
  2. 修正Axios调用格式:去掉多余的data参数,将所有配置合并到config对象中。

修正后的代码:

router.get("/test", async (req, res) => {
  let config = {
    headers: {
      client_id: process.env["BID"],
      client_secret: process.env["BSEC"],
      scope: process.env["BSCOPE"],
      grant_type: "client_credentials", // 根据实际认证场景调整值
    },
  };

  const apimUrl = "https://gateway-test.hapi.hmgroup.com/hapi-utils-auth/token";
  axios
    .get(apimUrl, config)
    .then((response) => {
      console.log(response.data);
      res.send(response.data);
    })
    .catch((error) => {
      console.log(error);
    });
});
  1. 额外排查点:
    • 打印process.env["BID"]、process.env["BSEC"]、process.env["BSCOPE"]确认环境变量是否正确加载。
    • 如果APIM代理实际要求使用POST方法(而非GET),可改为axios.post(apimUrl, {}, config)(POST方法第二个参数为请求体,此处不需要可传空对象)。

内容的提问来源于stack exchange,提问作者SSG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 11:22:04