Olivier
Olivier

Reputation: 445

Call a function in a Postman request

I need to call a function that returns the current date. I have to call this function in an object (contained in the body of my query). This object has a property whose value is the current date.

I wrote the function code as follows in the "pre-request scripts" of a POST request:

function currentDate() {
    let currentDate = new Date();
    return formatDate(currentDate);
};

function formatDate(date) {
    return [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(n => n < 10 ? `0${n}` : `${n}`).join('-');
};

Here is the property of the object in the body of my request:

enter image description here

Here is the error I get in console:

enter image description here

Thanks for your help

Upvotes: 1

Views: 2850

Answers (1)

Christian Baumann
Christian Baumann

Reputation: 3434

Try to set an environment variable with the current date at the end of the pre-request script:

pm.environment.set("currentDate", currentDate());

Then use that in your request body:

"start": "{{currentDate}}"

Upvotes: 1

Related Questions