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
- Invalid JSON Request Body: You're directly concatenating
clientIdandapiTokenas the raw body, which isn't valid JSON. The auth API expects a properly structured JSON object with your credentials. - Syntax Errors: Extra closing curly braces (
}) are scattered throughout the script, breaking the code's structure and causing execution failures. - Variable Scope Problem: The
requestvariable is defined inside theifblock. If the token is still valid (theifcondition isn't triggered),requestwill be undefined whenpm.sendRequestruns, leading to another error. - Typos:
Content-Type:application/Jsonuses a capital "J" — it should be lowercasejsonto 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 yourclient_idandapi_tokeninto 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.sendRequestinside theifblock so it only runs when we actually need a new token. This eliminates the undefinedrequestvariable issue. - Added Error Handling: Included a check for
errto handle cases where the token request fails, making debugging easier. - Corrected Content-Type: Changed
application/Jsontoapplication/jsonto 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
相关产品推荐
相关产品推荐

