Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
E6 Ajax request not working

I have a script where I want to fetch some json data from an endpoint, but I get an error, this is my script:

function httpGet(url) {
    return new Promise(
        function (resolve, reject) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (this.status === 200) {
                    // Success
                    resolve(this.response);
                } else {
                    // Something went wrong (404 etc.)
                    reject(new Error(this.statusText));
                }
            }
            request.onerror = function () {
                reject(new Error(
                    'XMLHttpRequest Error: '+this.statusText));
            };
            request.open('GET', url);
            request.send();
        });
}

var url = 'https://api.jsonPlaceholder.com';

httpGet(url)
  .then(JSON.parse)
  .then((r) => {
    console.log(r);
  }).catch(function(error) {
    console.log(error);
  });

Then, in the console it throws an error:

Error at XMLHttpRequest.request.onreadystatechange (app.js:11) at app.js:18 at Promise () at httpGet (app.js:2) at app.js:25

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can't just check status, you have to check for readyState == 4 before you can decide what happened:

function httpGet(url) {
    return new Promise(
        function (resolve, reject) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (this.readyState === 4) {                            // ***
                    if (this.status === 200) { 
                        // Success
                        resolve(this.response);
                    } else {
                        // Something went wrong (404 etc.)
                        reject(new Error(this.statusText));
                    }
                }                                                       // ***
            }
            request.onerror = function () {
                reject(new Error(
                    'XMLHttpRequest Error: '+this.statusText));
            };
            request.open('GET', url);
            request.send();
        });
}

The spec says accessing this.response before the request is complete should just return an empty string, but for me using Chrome v57, doing so gives the error you quoted. Adding the readyState check fixes it.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda