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

97
Visualizações
JS xmlhttprequest post query

I`m trying to create a post request using xmlhttprequest. This code just prints FAIL:

var data = JSON.stringify({
    text: "text",
    baseUrl: "url1",
  });

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;

  xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
      Console.log(this.responseText);
    }
  });

  xhr.open("POST", "url2");
  xhr.setRequestHeader("Authorization", "Bearer xxxx");
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.setRequestHeader("Accept", "application/json");
  );
  xhr.send(data);
  xhr.onload = function () {
    if (xhr.status == 200) {
      var h = xhr.response.text;
      console.log(h);
    }
  };
  xhr.onerror = function() {
    alert("FAIL");
  };

What`s wrong here? Or is it easier to use any other instruments for making requests? I've tried to use fetch like that:

function query() {
  const data = {
    "text": 'text',
    "baseUrl": "url"
  };
  let response = fetch('url', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      "Content-type": "application/json",
      "Authorization": "Bearer xxxx"
    },
    body: JSON.stringify(data)
  });
  console.log(response.status);
  let result = response.json;
  console.log(result.message);
}
query();

But it throws an exception too: Error: TypeError: Failed to fetch How to solve it?

about 4 years ago · Juan Pablo Isaza
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