2016-05-19 64 views
4

我是新來的離子和角。我正在使用angular.js構建帶有離子框架的示例。我想通過$ http post方法調用WebApi。我檢查了這個(ionic-proxy-example)解決方案,我試圖用我的api實現相同的功能。當我在示例項目中調用上述示例中提供的api時,我得到了記錄,但它不能用於我的api。它會拋出500個內部錯誤。

這裏是我的app.js

angular.module('myApp', ['myApp.controllers', 'myApp.services']) 
.constant('ApiEndpoint', {url: 'http://localhost:8100/api'}) 

Services.js

angular.module('myApp.services', []) 
.factory('Api', function($http, $q, ApiEndpoint) { 


console.log('ApiEndpoint', ApiEndpoint) 

var getApiData = function() { 
var q = $q.defer(); 

     var data = { 
      Gameweek_ID: '179', 
      Vender_ID: '1', 
      Language:'en' 
     }; 

     var config = { 
      headers : { 
       "Content-Type": "application/json; charset = utf-8;" 
      } 
     }; 

     $http.post(ApiEndpoint.url, data, config) 
     .success(function (data, status, headers, config) { 
      // $scope.PostDataResponse = data; 
       alert('success'); 
       console.debug("response :" + data); 
       q.resolve(data); 
     }) 
     .error(function (data, status, header, config) { 
      // $scope.ResponseDetails = "Data: " + data + 
       alert('error'); 
       console.debug("error :" + data); 
       q.reject(data); 
     }); 


return q.promise; 


} 

return {getApiData: getApiData}; 
}) 

controllers.js

angular.module('myApp.controllers', []) 
.controller('Hello', function($scope, Api) { 
$scope.employees = null; 
Api.getApiData() 
.then(function(result) 
{console.log("result is here"); 
jsonresponse = result.data; 
$scope.employees = jsonresponse;} 
) 

});

而且Ionic.Project文件

{ 


"name": "Multilingual", 
"app_id": "4b076e44", 
"proxies": [ 
{ 
    "path": "/api", 
    "proxyUrl": "" 
} 
]} 

我想了解的問題,並檢查多種方法來調用API。令人驚訝的是,它可以在沒有任何CORS錯誤的情況下使用ajax調用。當我使用Angular時,我試圖通過$ http post來完成此操作。我覺得這是一個小問題,但我無法弄清楚。將感謝解決方案。謝謝。

+0

你從哪裏得到前端應用程序或後端的錯誤?還請在開發者控制檯/網絡中檢查您的請求是什麼樣的,並仔細檢查您發送的網址 – MayK

+0

錯誤發生在瀏覽器上,當瀏覽器向api發送請求時。當我在Fiddler上ping時,我會得到結果。 – KKV

+0

你在後端獲得了什麼?你的後端是否期待任何xcrf令牌? – MayK

回答

0

的問題是,您要發送與$http.post請求而不是與$http.get

+0

api被配置爲接收POST請求。我正在明確發送「數據」。 – KKV

0

一個GET請求的POST嘗試爲如下─

$http({ 
      url: ApiEndpoint.url, 
      method: "POST", 
      data: data, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
     }).Success(..rest code goes here..) 

在的WebAPI,當我們通過在POST多個對象方法,我們得到500內部錯誤,因此我們在這種情況下使用ViewModel(談論asp.net MVC)。

2

您已經將內容類型設置爲json,因此服務器期望使用json字符串,但是在通過對象發送錯誤時沒有收到格式正確的json字符串。

如果您有$http.post(ApiEndpoint.url, data, config)更改爲$http.post(ApiEndpoint.url, JSON.stringify(data), config)

如果不工作,改變你的內容類型application/x-www-form-urlencoded並更新此行$http.post(ApiEndpoint.url, data, config)$http.post(ApiEndpoint.url, $httpParamSerializer(data), config),不要忘記注入$httpParamSerializer功能。

相關問題