2016-05-19 67 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功能。

相关问题