Search code examples
javascriptscriptingpostmanglobal-variablesresponse-headers

Postman Request Scripting: Extracting Values From Response And Setting Global Variable Values


I am writing a pre-request script in Postman which is meant to set the value of a global variable, API_TOKEN.

pm.sendRequest({
    url: pm.globals.get("GET_API_TOKEN_URL"),
    method: "GET",
    header: {
        clientId: pm.globals.get("GET_API_TOKEN_CLIENT_ID"),
        clientSecret: pm.globals.get("GET_API_TOKEN_CLIENT_SECRET")
    }
}, function (error, response) {
    console.log(response)
    console.log(response.header)
    pm.globals.set("API_TOKEN", response.header[3].apitoken)
})

My issue is that console.log(response.header) logs undefined, even though console.log(response) logs an object with various fields just fine:

{
    id: ...
    status: ...
    code: ...
    header: [11]
    ...
}

Thanks in advance!


Solution

  • the trick was to access response.headers.all()[3].value instead of response.header[3].value.

    https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/

    pm.sendRequest({
        url: pm.globals.get("GET_API_TOKEN_URL"),
        method: "GET",
        header: {
            clientId: pm.globals.get("GET_API_TOKEN_CLIENT_ID"),
            clientSecret: pm.globals.get("GET_API_TOKEN_CLIENT_SECRET")
        }
    }, function (error, response) {
        console.log(error ? error : response)
        if (error) {
            return
        } else {
            pm.globals.set("API_TOKEN", response.headers.all()[3].value)
        }
    })