【发布时间】:2016-09-15 21:01:45
【问题描述】:
我是 Ionic 和 Angular 的新手。我正在使用 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 的方法。令人惊讶的是,它可以与 ajax 后调用一起使用,而不会出现任何 CORS 错误。当我使用 Angular 时,我试图通过 $http post 来完成这项工作。我觉得这是一个小问题,但我无法弄清楚。将不胜感激解决方案。谢谢。
【问题讨论】:
-
前端应用程序或后端的错误是从哪里得到的?还要在开发者控制台/网络中检查您的请求是什么样的,并仔细检查您发送的网址
-
浏览器上的错误,当浏览器向api发出请求时。我在 Fiddler 上 ping 时得到结果。
-
你在后端得到了什么?您的后端是否需要任何 xcrf 令牌?
-
当我在没有设置代理的情况下进行简单的 $http 发布时,我在 mozilla 和 chrome 上遇到了跨源资源共享 (CORS) 错误。然后,我检查了这篇帖子 blog.ionic.io/handling-cors-issues-in-ionic 在客户端设置代理,以绕过我在链接中提供的演示中能够做到的 CORS。
标签: angularjs node.js ionic-framework gulp