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

Postman预请求脚本生成Bearer Token失败,请求排查错误原因

Fixing Postman Pre-Request Script for Bearer Token Generation

First, let's unpack the error you're hitting: "There was an error in evaluating the Pre-request Script: Error: No data, empty input at 1:1 ^" — this stems from a few key issues in your script, mostly invalid JSON formatting, syntax mistakes, and variable scope problems. Let's fix this step by step.

Issues in Your Original Script

  1. Invalid JSON Request Body: You're directly concatenating clientId and apiToken as the raw body, which isn't valid JSON. The auth API expects a properly structured JSON object with your credentials.
  2. Syntax Errors: Extra closing curly braces (}) are scattered throughout the script, breaking the code's structure and causing execution failures.
  3. Variable Scope Problem: The request variable is defined inside the if block. If the token is still valid (the if condition isn't triggered), request will be undefined when pm.sendRequest runs, leading to another error.
  4. Typos: Content-Type:application/Json uses a capital "J" — it should be lowercase json to match standard HTTP header conventions and your body mode.

Corrected Script

var expiresOn = pm.variables.get('ExpiresOn');
// Only fetch a new token if it's missing or expired
if (!expiresOn || new Date(expiresOn) <= new Date()) {
    var clientId = '565v7677676vfdrd';
    var apiToken = '6565fdvdrdfd';
    var request = {
        url: 'http://.../auth/token',
        method: 'POST',
        header: 'Content-Type: application/json', // Fixed typo and added space for readability
        body: {
            mode: 'application/json',
            raw: JSON.stringify({ // Wrap credentials in a valid JSON object
                client_id: clientId,
                api_token: apiToken
            })
        }
    };

    pm.sendRequest(request, function (err, res) {
        if (!err && res) { // Check for errors first to avoid crashes
            var json = res.json();
            pm.environment.set('Access_Token', json.access_token);
            // Calculate and store expiration date correctly
            var expiresOn = new Date(0);
            expiresOn.setUTCSeconds(json.expires_on);
            pm.environment.set('ExpiresOn', expiresOn);
        } else {
            console.error('Failed to fetch token:', err ? err.message : 'No response received');
        }
    });
}

Key Changes Explained

  • Valid JSON Body: Used JSON.stringify() to convert an object containing your client_id and api_token into proper JSON. This fixes the "empty input" error, as the auth API now receives valid data.
  • Fixed Syntax: Removed the extra closing braces that were breaking the script's structure.
  • Restricted Request Execution: Moved pm.sendRequest inside the if block so it only runs when we actually need a new token. This eliminates the undefined request variable issue.
  • Added Error Handling: Included a check for err to handle cases where the token request fails, making debugging easier.
  • Corrected Content-Type: Changed application/Json to application/json to align with standard HTTP practices.

Once you use this corrected script, set your collection's authorization type to "Bearer Token" and reference the {{Access_Token}} variable — it will automatically refresh whenever the token expires, so you won't need to manually input it anymore.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:33:55