5

I am using postman to get response header value like below:

var data = postman.getResponseHeader("Location") . //value is "http://aaa/bbb" for example 

I can print the value via console.log(data) easily.

However, what I really want is "bbb". So I need some substring() type of function. And apparently 'data' is not a javascript string type, because data.substring(10) for example always return null.

Does anyone what i need to do in this case?

If any postman API doc existing that explains this?

Divyang Desai
  • 6,470
  • 11
  • 40
  • 62
user1559625
  • 2,382
  • 2
  • 27
  • 56
  • is that exact error what you get? – ewwink Jan 08 '19 at 04:13
  • actually only toString() is needed firstly to convert it to javascript string, then it's self explanatory. – user1559625 Jan 10 '19 at 07:57
  • Does this answer your question? [How can I get last characters of a string](https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string) – Henke Feb 02 '21 at 13:21

3 Answers3

2

You can set an environment variable in postman. try something like

var data = JSON.parse(postman.getResponseHeader("Location"));
postman.setEnvironmentVariable("dataObj", data.href.substring(10));
Bhoomi
  • 89
  • 8
1

Some initial thought - I needed a specific part of the "Location" header like the OP, but I had to also get a specific value from that specific part. My header would look something like this

https://example.com?code_challenge_method=S256&redirect_uri=https://localhost:8080&response_type=code&state=vi8qPxcvv7I&nonce=uq95j99qBCGgJvrHjGoFtJiBoo

And I need the "state" value to pass on to the next request as a variable

var location_header = pm.response.headers.get("Location");
var attributes = location_header.split('&');

console.log(attributes);

var len = attributes.length;
var state_attribute_value = ""
var j = 0;
for (var i = 0; i < len; i++) {
    attribute_key = attributes[i].split('=')[0];
    if (attribute_key == "state") {
        state_attribute_value = attributes[i].split('=')[1];
    }
    j = j + 1;
}
console.log(state_attribute_value);
pm.environment.set("state", state_attribute_value);

Might you get the point here, "split" is the choice to give you some array of values. If the text you are splitting is always giving the same array length it should be easy to catch the correct number

Jan Nielsen
  • 191
  • 1
  • 5
1

You have the full flexibility of JavaScript at your fingertips here, so just split the String and use the part after the last /:

var data = pm.response.headers.get("Location").split("/").pop());

See W3 school's documentation of split and pop if you need more in depth examples of JavaScript internals.

Stefan Haberl
  • 7,787
  • 6
  • 59
  • 64