I have 2 Postman requests in a collection that the first request should run before the second request runs.
The first request is a POST request and it’ll give you a messageId in the repsonse body,
{
"messageId": "test-abcdefg",
"messageStatus": "PUSHED"
}
and the second request is a GET request and it passes the messageId in the url,
https://abcd.com.au/stp/v1/aaa/abcd@account/{{messageId}}
So, in the second request I have added a placeholder in the url to pass the messageId. and I’ve written a Pre-request script to run the first request and pass a value from it to the second request.
Here is my Pre-request script,
pm.sendRequest({
url: 'url',
method: 'POST',
header: {
'content-type': 'application/json'
},
body: {
mode: 'raw',
raw: [
{ key: "key1", value: 'abcd' },
{ key: "key2", value: '123456789' },
{ key: "key3", value: 1 },
{ key: "key4", value: 'abcd' }
]
}
}, (err, res) => pm.variables.set("messageId", res.json().messageId));
But, I’m getting the following error,
There was an error in evaluating the Pre-request Script:Error: Unexpected token '<' at 2:1 <!DOCTYPE html> ^
What did I do wrong?
Thanks in advance.
2
Answers
My understanding of the above pre-request script tells me that the post request you are sending, is sending you an error HTML page, that’s why it is not able to resolve the
res.json()
.Try changing
If this doesn’t work,
I would ask you to check the url that you are, sending in pre-request script or check body parameters that url requires. If those are as required, then check the Post API requirement for header type or authentication.
I hope this helps.
Pretty sure that the issue is just related to stringifying the body.
However, you could make the sendRequest more robust by adding a test or tests before you try and set the variable from the response.