"You need to configure the server side for access control, not the client."Well that's not entirely true.
The example I am using is based on the Spring, Jersey, run-as-ajar example you can find on GitHub. So lets start with the server side then:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@GET | |
@Path("/dates/{ticker}") | |
@Produces("application/json") | |
public Response getStatements(@PathParam("ticker") String ticker) { | |
try { | |
CompanyStatements companyStatements = fundamentalsDao.getStatementsForCompany(ticker); | |
GsonBuilder gsonBuilder = new GsonBuilder(); | |
gsonBuilder.registerTypeAdapter(Date.class, new DronzeDateSerializer()); | |
Gson gson = gsonBuilder.create(); | |
String json = gson.toJson(companyStatements); | |
return Response.status(Status.OK).entity(json) | |
.header("Access-Control-Allow-Origin", "*") | |
.header("Access-Control-Allow-Headers", "Content-Type") | |
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") | |
.build(); | |
} catch (Exception e) { | |
logger.error(e.getMessage(),e); | |
return Response.status(Status.INTERNAL_SERVER_ERROR) | |
.entity(getErrorJson()) | |
.build(); | |
} | |
} |
And here is the client side...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html ng-app="dronzeApp"> | |
<head> | |
<title>Hello World, AngularJS - ViralPatel.net</title> | |
<script type="text/javascript" | |
src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> | |
<script type="text/javascript"> | |
var dronzeApp = angular.module('dronzeApp', []); | |
dronzeApp.config(function($httpProvider) { | |
//Enable cross domain calls | |
$httpProvider.defaults.useXDomain = true; | |
//Remove the header containing XMLHttpRequest used to identify ajax call | |
//that would prevent CORS from working | |
delete $httpProvider.defaults.headers.common['X-Requested-With']; | |
}); | |
dronzeApp.controller('CompanyStatements', function ($scope, $http) { | |
$http.get('http://ec2-52-24-100-54.us-west-2.compute.amazonaws.com:8080/rest/api/statement/dates/AAN') | |
.success(function(data) { | |
$scope.statements = data; | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<div ng-controller="CompanyStatements"> | |
<div>Statement ticker: {{statements.ticker}}</div> | |
<ul> | |
<li ng-repeat="date in statements.statementDates"> | |
<span>{{date}}</span> | |
</li> | |
</ul> | |
<p>Total number of statements: {{statements.statementDates.length}}</p> | |
</div> | |
</body> | |
</html> |
No comments:
Post a Comment