首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在AngularJS中调用MVC?

在AngularJS中调用MVC?
EN

Stack Overflow用户
提问于 2014-05-06 00:19:02
回答 1查看 286关注 0票数 0

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

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文件:

代码语言:javascript
代码运行次数:0
运行
复制
<!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文件:

代码语言:javascript
代码运行次数:0
运行
复制
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;
            }
        );
    }
}]);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-07 13:16:07

为了给出一个答案:

$http.get('http://api.host.com/host');是您获得CORS/xhr异常的原因。因为该域与您的角应用程序不同,所以您的浏览器将其视为CORS请求。您有两个选择-处理服务器上的CORS请求,或设置相同的域并删除CORS问题。如果选择选项1,请参见设置允许您的请求的CORS响应头。如果您选择选项2(向localhost:发出请求),您所拥有的代码应该正确工作。

我回答了this question,我详细介绍了CORS的工作原理/浏览器如何处理CORS请求。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23483999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档