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

NestJs中Axios请求返回401错误,Postman正常运行求排查

问题排查:NestJS中Axios请求Keycloak返回401但Postman正常

核心问题分析及修复方案

1. 请求URL缺少协议

你的请求URL为localhost:8080/admin/realms/new/users,缺失http://或https://前缀。Axios对无协议URL的解析逻辑可能不符合预期,导致请求未正确发送至Keycloak服务,进而触发401验证失败。
修复:

`http://localhost:8080/admin/realms/new/users`

2. 请求体格式与Content-Type不匹配

你在请求头中声明Content-Type: application/json,但请求体却用querystring.stringify转换为表单格式字符串,这会导致Keycloak无法正确解析请求内容,最终触发权限验证失败。而Postman中你应该是发送的JSON格式请求体,所以能正常运行。
修复:直接传入JSON对象,无需通过querystring处理,同时注意enabled字段应该传布尔值而非字符串:

// 替换原请求体部分
{
  firstName: "Test",
  lastName: "last Test",
  email: "abc@tests.com",
  enabled: true,
  username: "new-user",
}

3. Token处理冗余(非401直接原因,优化代码)

当前token处理逻辑存在冗余操作:

const token = await this.newKeyToken(data); 
var string = JSON.stringify(token);
var objectValue = JSON.parse(string);
var bearerToken = objectValue['access_token'];

可直接简化为:

const token = await this.newKeyToken(data); 
const bearerToken = token.access_token;

4. 错误处理优化(非401原因,完善逻辑)

当前catch块仅打印错误,未将错误抛出,导致上层无法感知请求失败。修改为:

.catch((error) => {
  console.error(error);
  throw error; // 抛出错误让控制器处理异常
});

修复后的完整Service代码示例

async createKeycloakUser(data: any): Promise<any> {   
  const token = await this.newKeyToken(data); 
  const bearerToken = token.access_token;

  return this.httpService.axiosRef.post(
    `http://localhost:8080/admin/realms/new/users`,
    {
      firstName: "Test",
      lastName: "last Test",
      email: "abc@tests.com",
      enabled: true,
      username: "new-user",
    },
    {
      headers: { 
        "Authorization": `Bearer ${bearerToken}`,
        "Content-Type": "application/json",
      }
    }
  ).then(response => response.data)
  .catch((error) => {
    console.error(error);
    throw error;
  });     
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:01:02