Scheduling an async request

I cannot understand why the following code does not work

function sendRequest() {
    pm.sendRequest({
        url: 'https://website/signin',
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify({
                email: 'user@mail.com',
                password: 'xxxyyy'
            })
        }
    }, function (err, res) {
        if (err) {
            console.log(err);
        } else {
            pm.environment.set('token', res.json().token);
        }
    });
    
    setTimeout(sendRequest, 5 * 60 * 1000);
}
sendRequest();

It simply does not update the token. I tried using setInterval(sendRequest, 5 * 60 * 1000); instead, thinking there is some problem with the setTimeout function, but the same problem persists.

First of all, I don’t think you need to wrap this in a function. You are not sending any parameters to the function to make it worth being a function. pm.sendRequest itself is its own function which should suffice in this scenario. It’s just adding complexity.

Second thing is to console log your response before you set the environment variable.

Remember, the console log is your friend.

I would recommend parsing the response first, then console log it.

let jsonResponse = res.json();
console.log(jsonResponse);
pm.environment.set('token', jsonResponse.token);

Are you getting a valid response?

You also might want to consider wrapping the setting of the environment variable in a pm.test block, so that you don’t try and set the variable if the test fails. The test checking that the token exists in the response.

I wouldn’t include timeouts in your code, unless the server response is indicating that’s an issue.

Another troubleshooting step is to initially create this as individual request in the GUI. Does that work? (This should help you identify if there are timeout issues). This is a fairly basic request, so this should take ten minutes tops to create and test.

When I log the response, there is the token, but it still does not save the token in the environment.
I have declared the variable “token” in the environment and updated the Postman, just in case.

The website is ok. I need some solution for Postman so I can work on the API collection and do not have to log in every 5 minutes. If I don’t use the time out function and just put the sign in part in the pre-request of the parent folder it works. But it slows down the work. It is not the greatest solution.

*I am a beginner in this.

Can you console log the whole response for the sendRequest(), expand it out in the console and then share a screenshot?

I can only assume that the problem is with the targeting of the element.

On a side note, where are you running this from. The Collection Runner, or Newman?

Finally, is the environment selected and is everything saved?

Does the token include an expiry date, as you could also use that in your script to control whether it needs to get a new token.

The following is an example of authenticating to Microsoft with this concept.

pm.test("Check for collectionVariables", function () {
    let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
    vars.forEach(function (item, index, array) {
        console.log(item, index);
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty; 
    });

    if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) {
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
                    { key: "scope", value: pm.collectionVariables.get("scope"), disabled: false },
                    { key: "username", value: pm.collectionVariables.get("username"), disabled: false },
                    { key: "password", value: pm.collectionVariables.get("password"), disabled: false },                    
                    { key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                });
                let resJson = res.json();
                pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_in);
                pm.collectionVariables.set("bearerToken", resJson.id_token);
            }
        });
    }
});

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.