XMLHttpRequest in JS using setRequestHeader
-
Hello,
I want to get data from webradio and original script is:
"use strict"; const axios = require("axios"); const qs = require("qs"); //const { log } = require("abr-log")("meta-Djam Radio"); module.exports = async function(exturl) { try { const req = await axios({ method: 'POST', url: exturl, data : qs.stringify({ origin: 'website' }), headers: { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }}); const parsedResult = req.data; const curTrack = parsedResult["tracks"]["0"]; const picture = curTrack["pictures"][0]; return { artist:curTrack["artist"], title:curTrack["title"], cover: picture }; } catch (err) { return { error: err }; } }
I don't have axios in Qt then I try code below but it's returning "null":
function djamradio(url) { var res var xhr= new XMLHttpRequest() xhr.open('POST', url) xhr.setRequestHeader('Accept','application/json, text/javascript, */*; q=0.01') xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8') xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { // La constante DONE appartient à l'objet XMLHttpRequest, elle n'est pas globale var parsedResult = xhr.responseText; //var curTrack = parsedResult["tracks"]["0"]; //title=curTrack["title"] console.log(parsedResult) } }; xhr.send() }
url is: https://www.djamradio.com/actions/infos.php
How can I make it work please?
thank you for your help
-
Hi,
I haven't used that class yet but following your original call, shouldn't you be sending some data ?
Something like
xhr.send(qs.stringify({ origin: 'website'}))
? -
@SGaist
I try with JSON.stringify but result still emptyfunction djamradio(url) { var res var xhr= new XMLHttpRequest() xhr.open('POST', url) xhr.setRequestHeader('Accept','application/json, text/javascript, */*; q=0.01') xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8') xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { // La constante DONE appartient à l'objet XMLHttpRequest, elle n'est pas globale var parsedResult = xhr.responseText; //var curTrack = parsedResult["tracks"]["0"]; //title=curTrack["title"] console.log(parsedResult) } }; xhr.send(JSON.stringify({ origin: 'website'})) }
-
You have to check that the request was succesfull xhr.status == 200, probably the server answers you with an error and this is why you are getting xhr.responseText = null.
https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
Inspect if you are getting an http error code in xhr.status and the number to get more info.