AngularJS REST call to another server

2019-09-08 09:12发布

问题:

I'm using the Yeoman generator for AngularJS and I would like to interact with a REST server (who uses Spring Boot).

In my computer:

  • AngularJS app starts with Grunt on http://localhost:9000/
  • Spring Boot app is on http://localhost:8080/

In my AngularJS app I have a service like that :

angular.module('myApp')
  .factory('User', ['$resource',
    function($resource){
      return $resource('http://localhost:8080/poc/hello', {}, {
        query: {method:'GET'}
      });
  }]);

And here is the controller :

angular.module('myApp')
  .controller('RegisterCtrl', ['$scope', 'User', function($scope, User) {
      $scope.hello = User.query();
}]);

In my Java app :

@RestController("poc")
public class PocController {

    @RequestMapping("hello")
    public String getHello() {
        return "Hello World !";
    }
}

But when I want to do the call, I'm being blocked by "CORS"...

What is the best way to do what I want to do ? Not only for GET request, but POST, etc...

Is it possible to "configure" the REST server URL (http://localhost:8080/) once and make all AngularJS call (like /poc/hello) redirected to http://localhost:8080/poc/hello ? If yes, how ?

回答1:

set headers in your rest server, following is some data I set on my node server but the details should help:

'Access-Control-Allow-Origin': 'http://localhost:9000'
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE'
'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
'Access-Control-Allow-Credentials': false