Issue with loadJSON

How to use it for example with wikipedia api? On the request

loadJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=unicorn, gotData, 'jsonp')

I get a response in the form

Uncaught (in promise) TypeError: Cannot read property 'get' of undefined at VM70 p5.min.js:10

1 Like

hi @aliser,

-a- would be better to have the full code
or the link to the
https://editor.p5js.org/kll/sketches/Ywk8WgbK7

-b- so what is known is that there is a current problem about
CORS
means when you call to / from a https site
you see possibly no response,
but in ( context menue // right mouse click ) Inspect tab CONSOLE see

Failed to load 
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=p5js&utf8=&format=json: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'https://editor.p5js.org' is therefore not allowed access. 
If an opaque response serves your needs, 
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

you can play in above linked sketch
using url1 ( works ) or url2 ( wiki give error )
while a call in browser

https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=p5js&utf8=&format=json

usually works here.

1 Like

So ‘Access-Control-Allow-Origin’ is a server thing and we have to ask for permission or something like that and add to request ‘origin=*’. And there is a another option which uses xmlhttprequest.

Code:
https://editor.p5js.org/aliser/sketches/q_7DhSwYt

As @aliser has just mentioned, we need 'origin=*' for CORS, according to Wikipedia API’s docs: :spiral_notepad:
MediaWiki.org/wiki/API:Cross-site_requests

Here’s my own demo sketch for it: :sunglasses:

/**
 * JSON Wikipedia CORS Origin (v1.1.2)
 * GoToLoop (2019-Jan-21)
 *
 * https://Discourse.Processing.org/t/issue-with-loadjson/7682/4
 * https://Bl.ocks.org/GoSubRoutine/f13a55e7cfaabea6aa6bdf028c1f2f1e
 */

"use strict";

const HTTP = 'https://', SITE = 'en.Wikipedia.org',
      FOLD = '/w/', FILE = 'api.php',
      ASK  = '?', AND = '&',
      ORI  = 'origin=*',
      ACT  = 'action=opensearch',
      WORD = 'search=unicorn',
      LINK = HTTP + SITE + FOLD + FILE + ASK + ORI + AND + ACT + AND + WORD,
      LIST = 'ol', ITEM = 'li', BLANK = '_blank', COLOR = 'Red';

let jsonArray;

function preload() {
  print(LINK);
  jsonArray = loadJSON(LINK, print);
}

function setup() {
  noCanvas(), noLoop();
  console.table(jsonArray);

  const list = createElement(LIST)
          .style('color', COLOR)
          .style('font-weight: bold')
          .style('font-size: 1.2em');

  for (const url of jsonArray[3])
    createElement(ITEM).child(createA(url, url, BLANK)).parent(list);
    //createElement(ITEM, url.link(url)).parent(list);
}
2 Likes