Pieter-Jan
Pieter-Jan

Reputation: 1685

Angular Frontend with JAX-RS backend

I have a RESTful Java backend which I made using Jersey, a JAX-RS implementation. This backend is running on a glassfish server on port 8084. I've also made some HTML5/JS/AJAX pages which display the data so I know my REST implementation is working.

I'm trying to develop an HTML5 / JS frontend for this application using the Angular.js framework but I'm experiencing some trouble. I have managed to develop some small webapps in angular which I'm running on Microsoft's IIS on port 80.

Unfortunately, there appears to be a problem with the communication between the two applications. Since I'm new to Angular, I'm unsure if I made a mistake in my frontend code, or if I'm experiencing CORS problems. I already tried running the backend on a Tomcat 7 with the CORS filter but that didn't solve anything.

My angular code looks like this:

services.js

var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('NodeService', function($resource) {
var NodeService = $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{},
    {
        'get' : { method: 'GET',params:{port:':8084'}}
    }
)
return NodeService; 

});

controllers.js

function NodeDetailCtrl($scope, NodeService){
    var node3 = NodeService.get();
    $scope.data = JSON.stringify(node3) ;
}

I hardcoded the ID 3 for now, because I also need to figure out how I can pass the value of an input field from the view to the controller and then to the service. Eventually, the 3 in the service url would be replaced by a variable :nodeId

Any help would be greatly appreciated.

Upvotes: 2

Views: 2119

Answers (2)

Pieter-Jan
Pieter-Jan

Reputation: 1685

I found the solution. There were several steps to fix this problem:

  1. Add a CORS filter to the Jersey servlet on Glassfish.
  2. Upgrade the Angular version to 1.1.x (currently still unstable)
  3. Set a custom header in your resource.
  4. Enjoy a working application.

Big thanks Marcbaur for helping me out here.

Upvotes: 2

mooonli
mooonli

Reputation: 2393

Try the following simplified code:

app.js (for test purposes I suggest you to put functions in one js file)

var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('Node', function($resource) {
return $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{port:':8084'},
    {
        get {method:'GET'}
    });
});

serviceModule.controller('NodeDetailCtrl', function($scope, Node){
    $scope.data = Node.get();
}

It would be interesting to now what JSON data your client gets from the REST call.

Greets Marc

Upvotes: 3

Related Questions