使用$ http访问API内容类型的应用程序/ x-www-form-urlencoded总是会出现错误'结果

时间:2017-04-24 14:09:34

标签: angularjs object post serialization

我有以下REST服务,我必须访问POST方法, 我可以通过jQuery访问它,但我不知道如何使用AngularJSv1

<string xmlns = "http://schemas.microsoft.com/2003/10/Serialization/">
    <script id = "tinyhippos-injected" /> 
      {
        "volumeResult": {
            "gyydt": "9771241.17704773",
            "gytotal": "29864436.1770477",
            "gybudgeted": "29864436.1770477",
            "lyydt": "10197350",
            "lytotal": "27859381",
            "lybudgeted": "10197350",
            "cyytd": "6992208",
            "lastUpdate": "March-2017"
        },
        "valueResult": {
            "gyydt": "26862094",
            "gytotal": "68217952",
            "gybudgeted": "68232952",
            "lyydt": "0",
            "lytotal": "0",
            "lybudgeted": "0",
            "cyytd": "68217952",
            "lastUpdate": "March-2017"
        },
        "trucksResult": {
            "gyydt": "165951",
            "gytotal": "497879",
            "gybudgeted": "497879",
            "lyydt": "168822",
            "lytotal": "468814",
            "lybudgeted": "168822",
            "cyytd": "119442",
            "lastUpdate": "March-2017"
        }
    } 
</string>

这是我的 controller.js

angular.module('starter.controllers', [])
.controller('DashCtrl', ['$scope', '$http', function ($scope, $http) {

    $http({
        //headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
        headers: {'Content-Type' : 'application/json'},
        url: 'https://myurl../api/getHPData',
        method: 'POST',
        // data: data, 
        params: {
            "stationId": 263, 
            "crusherId": 27, 
            "monthYear": '2016-04'
        }
    })
    .then(function (response) {
                console.log(response);
     })
// I don't have to use .success and .error function as they are [depricated][2]

//.success(function (data, status, headers, config) {

//      $scope.greeting = data;
//      var Result = JSON.stringify(data);
//      var Result = JSON.parse(data);
//})
//.error(function (error, status, headers, config) {
//  console.log("====================== Error Status is: " + error);
//  console.log("====================== Status is: " + status);
//  console.log("====================== Error occured");
//})
}]) // eof controller DashCtrl

.controller('MapsCtrl', function($scope) {})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});

我想要的是: 的&#34; volumeResult&#34; &GT; &#34; gytotal&#34;

问题:

  1. 总是回归:
  2.   

    对象{数据:&#34; {&#34;结果&#34;:&#34; false&#34;}&#34;,状态:200,配置:对象,statusText:&#34;确定& #34;,header:function}

    1. 当我在没有引号的情况下传递monthYear时,它将(算术)处理为(2016-04 = 2012)

    2. 由于服务是POST,但当我在Chrome Developers Tool中进行分析时,我得到:(查询字符串,这不是故意POST)

    3.   

      ionic.bundle.js:25005   XHR完成加载:POST   &#34; https://myurl../api/getHPData?crusherId=27&monthYear=2016-4&stationId=263&#34;

      可能的解决方案: 要么我使用错误的标题:

      headers: {
               'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
               'Accept':       'application/json'
               },
      

      或标题可能是,

      headers: {
              'Content-Type': 'application/json', 
              'Accept':       'application/json'
              },
      

      或者根据我的朋友说:

        

      当我更改您的代码以使用上面的代码时,我收到此错误:   "{"Message":"The requested resource does not support http method 'OPTIONS'."}"这意味着存在CORS (Cross-origin Resource Sharing)问题。 Chrome正试图进行预检&#34;要求允许   CORS,但服务器不知道如何处理它。

      但我不认为这是因为我正在收到:

        

      对象{数据:&#34; {&#34;结果&#34;:&#34; false&#34;}&#34;,状态:200,配置:对象,   statusText:&#34; OK&#34;,headers:function}

      来自服务器。注意:{"result":"false"}是服务器在找不到数据传递错误的参数时显示的消息。另外,jQuery代码证明我可以访问服务器。 :)

      修改

      jQuery Snippet:

      <script>
      $(document).ready(function() {
              get_homepage_data(263, 27, '2016-04');
      
              function get_homepage_data(stationIds, crusherIds, date) {
                  var url = "https://myurl..";
                  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) {
      
                          // I know I can do it in one line but lazy enough to edit it here :p 
                          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>
      

      以上脚本的输出是脚本:

        

      价值是:{&#34; stationId&#34;:263,&#34; crusherId&#34;:27,&#34; monthYear&#34;:&#34; 2016-04&#34;}   XHR完成加载:POST&#34; https://myurl../api/getHPData&#34;。   foo的日志是:26862094   &#34; 26862094&#34;百万是:26.862094万   这确实很完美。 :)

2 个答案:

答案 0 :(得分:0)

尝试以这种方式使用$ http ..

$http.post("https://myurl../..",JSON.stringify({
            stationId: 263, 
            crusherId: 27, 
            monthYear:'2016-04'
        })).then(function(res){

          console.log(res);

        }).catch(function(errors){
          console.log(errors);
})

答案 1 :(得分:0)

我得到了答案。 Whao。

谢谢你georgeawg的回答:

他说:

发布经过网址编码的表单数据时,请使用$httpParamSerializer service转换请求:

$http({
    headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
    url: 'https://myurl..',
    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);
});

通常$http服务会自动解析JSON编码对象的结果,但此API返回一个已从对象进行双重序列化的字符串。 transformRespons e函数修复了这个问题。

现在我可以将gytotal的值设为:

    var myData = parseFloat(response.data.valueResult.gytotal);
    console.log(myData);