Skip to content

Instantly share code, notes, and snippets.

@knbknb
Forked from bcnzer/postman-pre-request.js
Last active August 7, 2019 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knbknb/61e8bcd6759b9fd7a294e037dce3b701 to your computer and use it in GitHub Desktop.
Save knbknb/61e8bcd6759b9fd7a294e037dce3b701 to your computer and use it in GitHub Desktop.
Postman pre-request script to automatically get a bearer token from our custom software 'mDIS' and save it for reuse
// set these variables on the folder level
// also select Postman No-Authentication option, and then set your own HTTP Autorization Header
var url = pm.variables.get('baseUrl') + "/api/v1/auth/login";
var username = pm.variables.get('username');
var password = pm.variables.get('password');
const echoPostRequest = {
url: url,
method: 'POST',
header: 'Content-Type:application/json',
body:
{
mode: 'urlencoded',
urlencoded: [
{ key: "username", value: username },
{ key: "password", value: password },
]
}
};
var getToken = true;
if (!pm.variables.get('currentAccessToken')) {
console.info(url + ': Token missing, will get new token...')
} else {
getToken = false;
console.info(url + ': Token is good');
}
console.log(echoPostRequest);
if (getToken === true) {
pm.sendRequest(echoPostRequest, function (err, res) {
if (err) {
console.log(err);
} else {
console.log('Saving the token')
var responseJson = res.json();
pm.variables.set('currentAccessToken', responseJson.token)
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment