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?