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

后端 未结 2 877
轻奢々
轻奢々 2020-12-11 11:56

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

2条回答
  •  天命终不由人
    2020-12-11 12:44

    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

提交回复
热议问题