0

更新:这是我在console.log $scope.Host = data; 行之前遇到的错误

XMLHttpRequest cannot load http://..... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52029' is therefore not allowed access.

我正在尝试调用返回 JSON 数据的 API,我是 AngularJS 的初学者,我正在尝试做的是调用 API 并非常简单地显示数据。

我的 HTML 文件:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>My AngularJS App</title>
    <script src="../scripts/angular.js"></script>
</head>
<body>
    <div data-ng-app="MyModule">

        <table class="table" data-ng-controller="MyModuleCtrl">
            <tr>
                <th>
                    FirstName
                </th>
                <th>
                    MiddleName
                </th>
                <th>
                    LastName
                </th>
                <th>
                    Email
                </th>
                <th>
                    Active
                </th>
            </tr>

            <tr>
                <td>
                    {{Host.FirstName}}
                </td>
                <td>
                    {{Host.MiddleName}}
                </td>
                <td>
                    {{Host.LastName}}
                </td>
                <td>
                    {{Host.Email}}
                </td>
                <td>
                    {{Host.Active}}
                </td>
            </tr>
        </table>
    </div>
    <script src="../scripts/MyApp/App.js"></script>
</body>
</html>

App.js 文件:

var MyModule = angular.module("MyModule", []);

MyModule.factory('MyHttpService',
    ['$http', function ($http) {

    return {
        getAll: function () {
            return $http.get('http://api.host.com/host'); //it returns json data
        }
 };
}]);

MyModule.controller('MyModuleCtrl', ['$scope', '$http', '$window', 'MyHttpService', 
    function ($scope, $http, $window, MyHttpService) {

        load();

        function load() {
            MyHttpService.getAll().success(function (data) {
               $scope.Host = data;
            }
        );
    }
}]);
4

1 回答 1

1

为了提供答案:

$http.get('http://api.host.com/host');这就是您收到 CORS/xhr 异常的原因。由于该域与您的 Angular 应用程序的域不同,因此您的浏览器将其视为 CORS 请求。您有 2 个选择 - 在您的服务器上处理 CORS 请求,或者将域设置为相同并消除 CORS 问题。如果您选择选项 1,请查看设置允许您的请求的 CORS 响应标头。如果您选择选项 2(向 localhost:<urPo​​rt> 发出请求),您拥有的代码应该可以正常工作。

我回答了这个问题,我更详细地介绍了 CORS 的工作原理/浏览器如何处理 CORS 请求。

于 2014-05-07T13:16:07.947 回答