Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!