API POST error - not sure what's causing it

I’m trying to pull in RGB palette info from this cool color API - http://colormind.io/api-access/. I have it working in other API tools but when I place the code in P5 I get this error:

Uncaught TypeError: Cannot read property ‘split’ of undefined (: line 56)
TypeError: Failed to fetch

I’ve tried following the example in Reference but am stumped. Thx for whatever insights you can provide!

function preload() {
  // Get color palette from colormind.io API
  let url = 'http://colormind.io/api/';
  let postData = {'model':'default'}
  httpPost(url, 'json', postData);
}

function draw() {
  background(220);
  //nothing here yet
}

Hi,

If I run the code in the p5 web editor, I get this error :

TypeError {stack: ""}

This is somehow cryptic and I don’t really know what is the formatting behind this.

However the httpPost function is using the fetch function behind the scenes and I tried running that in a new tab (in Firefox):

fetch('http://colormind.io/api/', {method: 'POST', body: postData})
     .then(data => data.json())
     .then(json => console.log(json))
     .catch(err => console.log(err));

And effectively there’s an error related to CORS :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://colormind.io/api/. (Reason: CORS request did not succeed).

TypeError: NetworkError when attempting to fetch resource.

This is caused by the fact that the creators of colormind.io didn’t enabled CORS headers and allowed requests from all origins.

Since fetch is using the Cross-Origin Ressource Sharing policy, you can read more about it here :

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

I also tried the JavaScript example at the end of the api page and it still gives me a CORS error. Most of the time it’s really anoying specially with APIs but it’s meant to be a security layer.

So you can contact the API provider asking them to add the CORS headers.

You can also take a look at that nice article, specially the Solutions section :

2 Likes

Hi and thank you!
Ugh CORS. I should have guessed. I will email them and ask for CORS headers - good suggestion. Thanks a ton for digging into this for me.

1 Like