Problem when requesting API using Xmlhttprequest

Asked

Viewed 117 times

-1

I am developing a system in pure Javascript. (Yes I want to do, even knowing the limitations rsrsrs) However I can’t access the API as it generates the following error when I do some request for API.

Following is an attachment to the bug and my code:

Error: inserir a descrição da imagem aqui

Code:

var minhaPromisse = function () {
return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest');
    xhr.setRequestHeader("X-CMC_PRO_API_KEY", 'MINHA-KEY-DA-API');

    xhr.send();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                resolve(JSON.parse(xhr.responseText));
            } else {
                reject('Erro na requisição')
            }
        }
    }
});
}

minhaPromisse()
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error)
    });

1 answer

0

Try to insert this header after what you have already entered before submitting the request:

xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
  • Did not work, error persisted.

  • I edited my answer just now by chance tested with the code now or with what was before?

  • tested both, the old and the new

  • A question, by chance you are running this script by where? For this type of request to work is necessary to be performed through a local server. If you are only running the direct page in a browser it will not work.

  • I’m running on live-server

Browser other questions tagged

You are not signed in. Login or sign up in order to post.