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.