Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

angularjs - Accessing API with $http POST Content-Type application/x-www-form-urlencoded

I am trying to access this REST API, which accepts three parameters: stationId, crusherId, monthYear I am doing it like this in AngularJS as:

$http({
        //headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
        //headers: {'Content-Type': 'application/json; charset=UTF-8'},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
            'Accept':       'application/json'
        },
        url:    'https://myurl../api/getHPData',
        method: 'POST',
        data: {
            stationId: 263, 
            crusherId: 27, 
            monthYear: '2016-4'
        }
    })

    .then(function(data, status, headers, config) {
            //console.log(JSON.stringify(response));
            console.log(data);
     })
    .catch(function(error){
            //console.log("Error: " + JSON.stringify(error));
            console.log(error);
        })

But I am always getting this:

Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}

OR

{"data":"{"result":"false"}","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":"OK"}

If I change header Content-Type to:

headers: {'Content-Type': 'application/json; charset=UTF-8'},

It gives:

Object {data: null, status: -1, config: Object, statusText: "",headers: function}

OR

{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/json; charset=UTF-8","Accept":"application/json, text/plain, /"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":""}

What I am doing wrong, Please help me.

Plunker is here:

https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview

(Edit)

Note: I can do it in jQuery as:

<script>
$(document).ready(function() {
        get_homepage_data(263, 27, '2016-04');

        function get_homepage_data(stationIds, crusherIds, date) {
            var url = "https://myurl../api/getHPData";
            var data_to_send = {
                'stationId': stationIds, 
                'crusherId': crusherIds,
                'monthYear': date
            };

            console.log("Value is: " + JSON.stringify(data_to_send));
            //change sender name with account holder name
            //        console.log(data_to_send)
            $.ajax({
                url: url,
                method:   'post',
                dataType: 'json',
                //contentType: 'application/json',
                data: data_to_send,
                processData: true,
                // crossDomain: true,
                beforeSend: function () {
                }
                , complete: function () {}
                , success: function (result1) {
                    var Result = JSON.parse(result1);
                    var value_data = Result["valueResult"];
                    var foo = value_data["gyydt"];

                    console.log("Log of foo is: " + foo);

                    var foo2 = 0;
                    // 10 lac is one million.
                    foo2 = foo / 1000000 + ' million';

                    console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
                }
                , error: function (request, error) {
                    return false;
                }
            });
        }   
    }); // eof Document. Ready  
</script>

Output of above script is script is:

  • Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
  • XHR finished loading: POST "https://myurl../api/getHPData".
  • Log of foo is: 26862094
  • "26862094" in million is: 26.862094 million

Which is perfect. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:

$http({
    headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
    url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
    method: 'POST',
    transformRequest: $httpParamSerializer,
    transformResponse: function (x) {
      return angular.fromJson(angular.fromJson(x));
    },
    data: {
      "stationId": 263,
      "crusherId": 27,
      "monthYear": '2016-04'
    }
}) 
  .then(function(response) {
    console.log(response);
    $scope.res = response.data;
    console.log($scope.res);
});

Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.

The DEMO on PLNKR


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...