AngularJS和REST服务 [英] AngularJS and Rest Service

查看:152
本文介绍了AngularJS和REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始尝试用 AngularJS 。我建立了一个简单的HTML5应用程序,一个更新的 MySQL的数据库。

I've recently started experimenting with AngularJS. I am building a simple html5 application that updates a MySQL database.

[index.html的]

<!DOCTYPE html>
<html ng-app="MyProject">
<head>
    <title>My Project</title>
    <link rel="stylesheet" href="css/main.css" type="text/css">
    <script src="lib/angular-1.0.1.js"></script>
    <script src="lib/angular-resource-1.0.1.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
</head>
<body>
    <div id="main-content" ng-view>
</body>
</html>

我用了超薄框架来创建一个REST接口。我的数据库目前有两列ID和标题一个表命名location_types。我已经在浏览器中测试的REST服务,以便根据API / locationtypes我得到以下JSON:

I used the Slim framework to create a Rest Interface. My database has currently one table named location_types with two columns id and title. I have tested the Rest service in the browser so under api/locationtypes I get the following JSON:

[{"id":"1","title":"Airport"},{"id":"2","title":"Bus Station"}]

我在创建使用以下code AngularJS服务:

I create the service in AngularJS using the following code:

[services.js]

angular.module('myDB', ['ngResource']).
factory('LocationTypes', function($resource) {
    var LocationTypes = $resource('http://localhost/project/api/locationtypes', {}, { query: {method: 'GET', isArray: true}});
    return LocationTypes; 
});

我也用下面的code创建应用程序模块:

I also use the following code to create the app module:

[controllers.js]

angular.module('MyProject', ['myDB']).
config(function($routeProvider) {
    $routeProvider.
        when('/locationtypes', {controller: LocationTypesCtrl, templateUrl:'forms/locationtypes.html'}).
        otherwise({redirectTo:'/locationtypes'});
});


function LocationTypesCtrl($scope, LocationTypes)
{
    $scope.locationTypes = LocationTypes.query();
}

问题是,我没有得到任何结果查询售后服务。在 locationTypes 数组的长度为零,当我调试。我使用的是最新的AngularJS版本[1.0.1]。我怎么错过?

The problem is that I get no results after querying the service. The locationTypes array is of zero length when I debug. I am using the latest AngularJS release [1.0.1]. What do I miss?

推荐答案

可能是一个问题CORS像丹说。
您可以通过添加以下到您的模块配置绕过这个。

Probably a CORS issue like Dan said. You can bypass this by adding the following to your module config.

.config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
})

删除由角设置应该解决这个问题CORS头。
你也应该在您的API文件夹中添加一个.htaccess文件。并补充一点:

Deleting the headers set by Angular should resolve the CORS issue. You should also add a .htaccess file in your api folder. And add this:

Header set Access-Control-Allow-Origin "*"

这篇关于AngularJS和REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆