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

Postman预请求脚本无法获取OAuth token问题求助

解决Postman预请求脚本OAuth续期时的invalid_client错误

你遇到的invalid_client错误核心原因是:虽然设置了Content-Type: application/x-www-form-urlencoded,但脚本里的请求体没有按照该格式正确构造。手动发送请求时Postman会自动处理表单编码,但pm.sendRequest需要明确指定请求体的模式。

修改方案:将请求体的结构调整为urlencoded模式,把参数放在urlencoded数组中,每个参数用key和value定义。

修改后的完整脚本:

// Refresh the OAuth token if necessary
var tokenDate = new Date(2010,1,1);
var tokenTimestamp = pm.environment.get("OAuth_Timestamp");
if(tokenTimestamp){
  tokenDate = Date.parse(tokenTimestamp);
}
var expiresInTime = pm.environment.get("ExpiresInTime");
if(!expiresInTime){
    expiresInTime = 300000; // Set default expiration time to 5 minutes
}
if((new Date() - tokenDate) >= expiresInTime) 
{
   pm.sendRequest({
      url: pm.variables.get("base_url_token"), 
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: {
        mode: 'urlencoded',
        urlencoded: [
            { key: 'grant_type', value: 'password' },
            { key: 'username', value: pm.environment.get("username") },
            { key: 'password', value: pm.environment.get("password") },
            { key: 'client_id', value: pm.environment.get("client_id_practice_app") },
            { key: 'client_secret', value: pm.environment.get("client_secret_practice_app") }
        ]
      }
  }, function (err, res) {
        if (err) {
            console.error(err);
            return;
        }
        pm.environment.set("OAuth_Token", res.json().access_token);
        pm.environment.set("OAuth_Timestamp", new Date());
        
        // Set the ExpiresInTime variable to the time given in the response if it exists
        if(res.json().expires_in){
            expiresInTime = res.json().expires_in * 1000;
        }
        pm.environment.set("ExpiresInTime", expiresInTime);
  });
}

额外优化:在回调函数里增加了错误捕获,方便排查后续可能出现的问题。

内容的提问来源于stack exchange,提问作者Jakob Busk Sørensen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:20:41