Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda