gpt4 book ai didi

javascript - 授权承载 token 的 postman 预请求脚本

转载 作者:行者123 更新时间:2023-11-28 03:24:28 26 4
gpt4 key购买 nike

我正在尝试编写脚本来生成集合的身份验证承载 token 。所以我不必每次都传递 token ,我将从父级继承身份验证。但我不知道脚本哪里错了,我无法生成 token ,它给了我错误

There was an error in evaluating the Pre-request Script:  Error: No data, empty input at 1:1 ^

这是我的脚本,

var expiresOn = pm.variables.get('ExpiresOn');
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',
body: {
mode: 'application/json',
raw: clientId + apiToken
}
};
}
};

pm.sendRequest(request, function (err, res) {
if (res !== null) {
var json = res.json();
pm.environment.set('Access_Token', json.access_token)

var expiresOn = new Date(0);
expiresOn.setUTCSeconds(json.expires_on);
pm.environment.set('ExpiresOn', expiresOn);
}
});
}

最佳答案

const echoPostRequest = {
url: 'https://example.com/sign_in?client_id=dbdsA8b6V6Lw7wzu1x0T4CLxt58yd4Bf',
method: 'POST',
header: 'Accept: application/json\nUser-Agent: Example/2019.10.31-release (Android 6.0.1; LGE Nexus 5)\nUDID: 1d2c7e65f34b3882f8e42ab8d6a82b4b\nContent-Type: application/json; charset=utf-8\nHost: api-mobile.example.com',
body: {
mode: 'application/json',
raw: JSON.stringify(
{
client_id:'dbdsA8b6V6Lw7wzu1x0T4CLxt58yd4Bf',
client_secret:'aBK1xbehZvrBw0dtVYNY3BuJJOuDFrYs',
auth_method:'password',
create_if_not_found:false,
credentials:{identifier:'username',password:'pass'},
signature:'2:a899cdc0'
})
}
};

var getToken = true;

if (!pm.environment.get('accessTokenExpiry') ||
!pm.environment.get('currentAccessToken')) {
console.log('Token or expiry date are missing')
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
console.log('Token is expired')
} else {
getToken = false;
console.log('Token and expiry date are all good');
}

if (getToken === true) {
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token and expiry date')
var responseJson = res.json();
pm.environment.set('currentAccessToken', responseJson.access_token)

var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
});
}
上面的示例是一个 Postman 预请求脚本,用于获取 access_token 以及 token 的过期时间。我想这个例子会帮助你解决这个问题。请检查 postman 的控制台在 Windows 上按 Ctrl+Alt+C(在 Mac 上按 Cmd + Alt+C)打开 Postman 控制台

enter image description here

关于javascript - 授权承载 token 的 postman 预请求脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58775532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com