1

I am trying to make a simple POST request to http://battle.platform45.com/register The server is setup to respond with JSON. So from the command line:

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

successfully returns

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

I try to do the same thing in 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')
        })
    }
});

with a simple view:

<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>

When I try to make the request I get an error:

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. 

How does the POST request go through with curl but not angular? What can I do to successfully make the request with angular?

Connor Leech
  • 18,052
  • 30
  • 105
  • 150

2 Answers2

2

I believe battle.platform45 is not allowing web browsers to do direct calls to their servers. By default, websites from different domains cannot access API resources from other websites.

As according to platform45, you must use Rails to create a game. So I suggest creating your own server that will call from their API server. Then use your AngularJS code to access your server.

I hope this diagram can illustrate it better:

Battle.platform45 Server -- (is called by) --> Your Server -- (is called by) --> Your HTML/Angular JS Code

khakiout
  • 2,372
  • 25
  • 32
  • yeah it's an issue with platform45's server not allowing cors from browser. Now i gotta setup a node.js server to do the dirty work for me – Connor Leech May 08 '14 at 08:43
0

Try doing this:

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')
        })
    }
});
Ritesh Waghela
  • 3,474
  • 2
  • 19
  • 25