问题
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?
回答1:
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
回答2:
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')
})
}
});
来源:https://stackoverflow.com/questions/23535260/cross-origin-request-error-with-angularjs-1-2-6