In POSTMAN how do i get substring of response header item?

Viewed 11358

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?

3 Answers

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));

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.

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

Related