Estoy tratando de crear una solicitud de publicación usando xmlhttprequest. Este código simplemente imprime FALLO:
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"); };¿Qué está mal aquí? ¿O es más fácil utilizar otros instrumentos para realizar solicitudes? He intentado usar fetch así:
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();Pero también arroja una excepción: Error: TypeError: Failed to fetch ¿Cómo resolverlo?