0

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?

  • `"url2"` is not a valid url I guess...? Always check the browser console for errors. –  Apr 25 '22 at 06:29
  • @Chris yes thats Just an example. – polter soln Apr 25 '22 at 06:39
  • Ok, so did you check the XHR in the console? It should show *why* the request fails. Also, there's [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data) now –  Apr 25 '22 at 06:41
  • Do u mean i should use browser console to see the problem? And is it necessary to download something to use fetch? – polter soln Apr 25 '22 at 06:46
  • Press F12 to open the dev tools, then go to the Console tab. You may have to enable the display of XHRs first. And no, fetch is part of the browser's API. You can just use it. –  Apr 25 '22 at 06:48
  • N how to enable the display? Or is it going to enable automatically? – polter soln Apr 25 '22 at 06:58
  • In Firefox for instance, the top bar of the console tab has a bunch of toggle switches at the end. –  Apr 25 '22 at 07:02
  • @ChrisG can u help with fetch please? – polter soln Apr 25 '22 at 12:23
  • You can always switch to fetch once we find out what the issue is. What does the XHR look like in the console? You should see the cause of the error. –  Apr 25 '22 at 13:26
  • Reason: The CORS header "Access-Control-Allow-Origin" is missing – polter soln Apr 25 '22 at 13:48
  • Yep, that's very common. It usually means that whatever API you're trying to use cannot be used from inside a browser. You need to make the requests on your backend instead. –  Apr 25 '22 at 13:54
  • How can i do that using vscode? – polter soln Apr 25 '22 at 17:27
  • VS Code is basically a text editor. By backend I mean a server, written in PHP, Node, Python, etc. –  Apr 25 '22 at 17:28
  • Well, if i insert this code in [JsFiddle](https://jsfiddle.net) than it says that object responce is undefined. N I tried to make function `query` async but it would work at all and it prints nothing( – polter soln Apr 25 '22 at 18:17
  • Look, I can't teach you how HTTP works. The gist is that the API you're trying to use doesn't allow requests from code that runs inside a browser. So it doesn't matter where you're hosting the code, it won't work between , period. Like I told you, what you need is a web server. I know that beginners tend to believe they can magically circumvent technical restrictions that require learning a bunch of new things if they only manage to find just the right command or hint, but that's not how this works. You need to learn PHP or nodeJS or Flask or whatever. –  Apr 25 '22 at 18:34

0 Answers0