Day 25 - Async request error

LINK: Day 25 of 30 Postman

Iā€™m not sure what I am doing. From what I gather I am making a call to the color-API and echoing the response at postman.echo.

I believe the URL is OK: http://www.thecolorapi.com/id?hex=04151c

But I get this error in the console and am at a lossā€¦

image

PRE_REQUEST Script:


//get hex color
var hex_tmp = pm.variables.replaceIn('{{$randomHexColor}}')
var hex = hex_tmp.replace ("#","") //strip # 
pm.environment.set('hex',hex)

//create 'payload'
var body = 
        {
            hex: hex,
            rgb: "rgb(23, 13, 88)",
            name: "Violent Violet"
        };
var body_str = JSON.stringify(body);
pm.environment.set('payload', body_str);

//set URL
var url_tmp = 'https://www.thecolorapi.com/id?hex=' + pm.environment.get('hex')
var url_str = JSON.stringify(url_tmp);
pm.environment.set('url',url_str)

//sanity check
console.log(pm.environment.get('payload'))
console.log(pm.environment.get('url')) 

pm.sendRequest({
    url: pm.environment.get('url'),
    method: 'POST',
   // header: 'headername1:value1',
   function (err, res) 
   {
    console.log(res);
   }
});

Letā€™s check the instructions for that days task:


First thing I see is that youā€™re trying to send a POST request to the colour API, which it doesnā€™t accept and thatā€™s why itā€™s returning that error. If you change that to a GET it should be fine.

I would go a more reduced code route but it all get you to the same place in the end.

let hex = pm.variables.replaceIn('{{$randomHexColor}}');

pm.sendRequest(`https://www.thecolorapi.com/id?hex=${hex.replace('#', '')}`, function (err, response) {
    pm.variables.set("payload", JSON.stringify({
        hex: `${hex}`,
        rgb: `${response.json().rgb.value}`,
        name: `${response.json().name.value}`
    }))
});

After you have this working, ensure that youā€™re creating tests to check for a successful response and that it includes the properties.

Danny, you are my hero!! Thanks - I would have never figured this out!

I LOVE your code - concise! I esp appreciate the '${response.jason()ā€¦ - this is one of those things I couldnā€™t figure out.

I think one of the things that is really confusing is using variables:
{{variable}} - used in headers, query params
{{$variable}} - this is the built-in pseudo vars
{$variable} - I guess a template for receiving variable?
ā€˜variableā€™ - console.log(ā€˜variableā€™)
variable - guess just a JAVA variable
ā€¦Iā€™ll figure this out in time.

Thanks again!

The backticks are part of JavaScript templates strings.

The ${ā€¦} is using Interpolation.

JavaScript Template Strings (w3schools.com)

I use these all of the time to create custom test case names if I loop through a response.

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