DlgzRogelio / Project-1

MIT License
0 stars 1 forks source link

Store duck duck API result in an array #25

Closed DlgzRogelio closed 3 years ago

ca2los commented 3 years ago

Hey Team, we have a problem.

As you may now, the Duck Duck API has some issues every time we want to retrieve data from it. The console prints messages like:

Access to fetch at 'https://api.duckduckgo.com/?q=Leonardo%20DiCaprio&format=json&pretty=1' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

In order to make it work, we had to test with different scripts to comprehend the reasons of this behavior:

@CONSOLE

    function duck_api() {
        let request_actor = 'Leonardo DiCaprio';
        let request_url = 'https://api.duckduckgo.com/?q=' + request_actor + '&format=json&pretty=1';
        fetch(request_url).then(function (response){
            return response.json();
        })
        .then(function(data) {
            console.log(data);
        });
    }
    duck_api();

... and ...

@CONSOLE

    function duck_api() {
        let request_actor = 'Leonardo DiCaprio';
        let request_url = 'api.duckduckgo.com/?q=' + request_actor + '&format=json&pretty=1';
        fetch(request_url).then(function (response){
            return response.json();
        })
        .then(function(data) {
            console.log(data);
        });
    }
    duck_api();
    const response = await fetch('https://api.duckduckgo.com/' , {
        'mode': 'cors',
        'headers': {
            'Access-Control-Allow-Origin': '*',
        }
    });

The next version is the more last and more advanced version. It was coded by @ltrevino and it almost works:

@CONSOLE

    function duck_api() {
        let headers = new Headers();
        let request_actor = 'Leonardo DiCaprio';
        let request_url = 'https://api.duckduckgo.com/?q=' + request_actor + '&format=json&pretty=1';
        headers.append('Access-Control-Allow-Origin', '*');
        fetch(request_url, {
            //mode: 'no-cors',
            headers: headers
        }).then(function (response){
            console.log(response);
            return response.json();
        }).then(function(data) {
            console.log(data);
        });
    }
    duck_api();

Finally @ltrevino found the answer:

The problem can't be solved because we must modify the server headers and obviously we don't own the server nor have the access to it.

Case closed?

Maybe, but there are 2 options:

  1. Initialize Chrome and disable security to run the API
  2. Look for a new API

cc @DlgzRogelio @ltrevino @ian-dot