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

二次信任 提交于 2019-11-28 13:05:09

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

The documentation says that the stationId and crusherId parameters should be arrays of strings. Also, it looks like you are sending JSON data, so make sure to set that header correctly.

$http({
    headers: {
        'Content-Type': 'application/json', 
        'Accept':       'application/json'
    },
    url:    'https://fnrc.gov.ae/roayaservices/api/getHPData',
    method: 'POST',
    data: {
        stationId: ['263'], 
        crusherId: ['27'], 
        monthYear: '2016-4'
    }
})

When I change the code in your plunkr to use the corrected code above, I get the following response: "The requested resource does not support http method 'OPTIONS'."

As the other (now deleted) answer correctly mentioned, this means that there is a CORS issue. The browser is trying to send a "preflight" request before making the cross-origin request, and the server doesn't know what to do with it. You can also see this message in the Chrome console:

XMLHttpRequest cannot load https://fnrc.gov.ae/roayaservices/api/getHPData. Response for preflight has invalid HTTP status code 405

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!