Need help, json method not working on fetch

Hey, I was trying to make Wikipedia viewer but fetch is not co-operating

const apiUrl = (q) => `https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=${q}`
    
const lol = apiUrl('lol')

fetch(lol, {'mode': 'no-cors'})
.then(blob => blob.json())
.then(K => console.log(K))

and I am getting this in browser
bug

can anyone tell how to get out of this problem.

Try adding origin=*, and making a normal cors request.

fetch(
    "https://en.wikipedia.org/w/api.php?&origin=*&format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=lol"
)
    .then(function(r) {
        return r.json();
    })
    .then(function(d) {
        console.log(d);
    });

As per https://www.mediawiki.org/wiki/Manual:CORS.

1 Like

You can get a hint of what is wrong if you do console.log(blob) before the call to blob.json(). blob is actually a Response. Its member ok is false, meaning the request failed, and its type is "opaque", which, according to MDN, means that “you used ‘no-cors’ for a cross-origin request” and the body is null. This is where your problem lies. You can’t get JSON data through an opaque response. An opaque response gives you very little data. See https://stackoverflow.com/questions/39109789/what-limitations-apply-to-opaque-responses for more info.

Wikipedia won’t let you access its API with a normal JSON query. You have to use either CORS or JSONP. I haven’t used fetch before so I can’t really advise how to do it. I know you can access Wikipedia with $.ajax() with datatype: 'jsonp' if that helps.

1 Like