jeudi 3 novembre 2016

Make Get Requests from my widget (Html, Css, Javascript) to my Web Api

I tested my Web Api Get methods in Postman application and I simply post the link in the browser and the results are all correct. However, when I try to make a get request in my widget, the result is always null and I don't know why.

  • For example, for this method in my WEB API (the result is in XML):

Return all "Sensores" from my database.

    // GET: api/Sensor
    public IQueryable<SensorDTO> GetSensores()
    {
       var sensores = from p in db.Sensores 
           select new SensorDTO()
           {
            ID = p.ID,
            Nome = p.Nome,
            Descrição = p.Descrição,
    };

    return sensores;

    }

  • I make the get request of this method in my WIDGET (Javascript) as follows:

    function getSensoresCancela (){
     var url;
     var args = [];
    
     args[0]=2;
     url = "http://localhost:12345/api/sensor";
     makeXmlHttpGetCall(url, null, true, true, stateHandler, args);
    }
    
    

In this case, "response" is always null.

    function makeXmlHttpGetCall(url, params, async, xml, callback, args) {
        var xmlHttpObj = CreateXmlHttpRequestObject();
        if (xmlHttpObj) {
           xmlHttpObj.open("Get", url, async);
           xmlHttpObj.onreadystatechange = function() {
           if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) {
              var response;
              if (xml === true)
                 response = xmlHttpObj.responseXML;    // return null here
               else
                 response = xmlHttpObj.responseText;
               callback(response, args);
              }
           };
           xmlHttpObj.send(params);
        }
      }

    function CreateXmlHttpRequestObject() {

         if (window.XMLHttpRequest) {

            xmlHttpObj = new XMLHttpRequest();

         } else if (window.ActiveXObject) {

            xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");

        }
       return xmlHttpObj;
    }




Aucun commentaire:

Enregistrer un commentaire