【问题标题】:cross origin request error with angularjs 1.2.6angularjs 1.2.6 的跨域请求错误
【发布时间】:2014-06-25 11:03:54
【问题描述】:

我正在尝试向http://battle.platform45.com/register 发出一个简单的 POST 请求,服务器设置为使用 JSON 响应。所以从命令行:

$ curl --data '{"name": "Connor", "email": "connorleech@gmail.com"}' http://battle.platform45.com/register

成功返回

{"id":"3118","x":1,"y":9}%

我尝试在 Angular 中做同样的事情:

app.controller('BattleshipCtrl', function ($scope, $http) {
    $scope.game = {}
    $scope.newGame = function(name, email){
        $http.post("http://battle.platform45.com/register", { 
            name: name,
            email: email
        }).success(function(data, status, headers, config){
           console.log('Success')
        })
    }
});

简单的观点:

<input type='text' ng-model='game.name'>
<input type='text' ng-model='game.email'>
<div class='btn btn-success' ng-click='newGame(game.name, game.email)'>New game</div>

当我尝试发出请求时出现错误:

OPTIONS http://battle.platform45.com/register 404 (Not Found) angular.js:7962
XMLHttpRequest cannot load http://battle.platform45.com/register. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://0.0.0.0:9000' is therefore not allowed access. 

POST 请求如何通过 curl 而不是 Angular 进行?我该怎么做才能成功地使用 Angular 发出请求?

【问题讨论】:

    标签: javascript angularjs post http-post cors


    【解决方案1】:

    我相信battle.platform45允许网络浏览器直接调用他们的服务器。默认情况下,不同域的网站无法访问其他网站的API资源。

    根据platform45,您必须使用Rails 来创建游戏。所以我建议创建你自己的服务器,从他们的 API 服务器调用。然后使用您的 AngularJS 代码访问您的服务器。

    希望这张图能更好地说明:

    Battle.platform45 服务器 -- (被调用) --> 你的服务器 -- (被调用) --> 你的 HTML/Angular JS 代码

    【讨论】:

    • 是的,这是 platform45 的服务器不允许来自浏览器的 cors 的问题。现在我要设置一个 node.js 服务器来为我做脏活
    【解决方案2】:

    尝试这样做:

    var config = {headers: {
                'Access-Control-Allow-Origin': '*'
                }
        };
    
    app.controller('BattleshipCtrl', function ($scope, $http) {
        $scope.game = {}
        $scope.newGame = function(name, email){
            $http.post("http://battle.platform45.com/register", config, { 
                name: name,
                email: email
            }).success(function(data, status, headers, config){
               console.log('Success')
            })
        }
    });
    

    【讨论】:

    • 您使用的是哪个浏览器,您的应用托管在哪里?
    • 尝试将您的应用程序托管在 Web 服务器中,例如 apache http 服务器。
    • 如果您可以控制服务器端代码,则需要在响应中包含“Access-Control-Allow-Origin”标头,并将其值设置为您的域或 * 以供任何人访问。
    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 2018-01-03
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2014-08-04
    • 2014-04-19
    相关资源
    最近更新 更多