1

I am trying to access the JSON response from Spring application on a HTML page using AngularJS and getting "No 'Access-Control-Allow-Origin' header is present on the requested resource." error. The requested URL is http://174.142.61.106:8080/BMAppJ/learningresources/getlist/.

The HTML code is given below:

<html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script type="text/javascript">
  var app = angular.module('myApp', []);
 app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]); 
 app.controller('Hello', function($scope, $http) {
 
 $http.get('http://174.142.61.106:8080/BMAppJ/learningresources/getlist').
  success(function(data) {
   $scope.response = data;alert(response);
 });
  $scope.clickme=function(){
   var res = jQuery("#resource_type").val();
     $http.get('http://174.142.61.106:8080/BMAppJ/learningresources/getlist/'+res).
       success(function(data) {
         $scope.response = data;
      });
  }
});
 </script>
  </head>
  <body>
  <table width="100%"   ng-app="myApp" ng-controller="Hello">
      <tr><td><b>Resource Type</b></td><td><b>Resource Name</b></td></tr>
      
  <tr ng-repeat="x in response">
    <td>{{x.resourceType}}</td>
    <td>{{x.name}}</td>
  </tr>
</table>
    </body>
  </html>

The Spring service code is given below:

 @RequestMapping(value = "/getlist", method = RequestMethod.GET, produces = "application/json")
 public @ResponseBody ResponseEntity geResourceList(HttpServletRequest request, HttpServletResponse response){
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Access-Control-Allow-Origin", "*");
        logger.info("getAllResources() from ajax begins: ");
        Map resourceMap = null;
        JSONArray map = new JSONArray();
        try {
            logger.info("getAllResources() from ajax begin: ");

            List resourceList = resourceService
                    .getAllResources();
            java.util.Iterator resourceIterator = resourceList.iterator();
            while (resourceIterator.hasNext()) {
                resourceMap = new HashMap();
                ResourceModel model = resourceIterator.next();
                resourceMap.put("resourceType", "" + model.getResourceType());
                resourceMap.put("name", "" + model.getName());
                logger.info("" + model.getResourceType(),
                        model.getName());
                map.add(resourceMap);
            }
        } catch (Exception e) {
            logger.debug("Error while getting location in ajax request:"
                    + e.getMessage());
            e.printStackTrace();
        }logger.info("getAllResources() from ajax ENDS: ");
        return new ResponseEntity(map, responseHeaders, HttpStatus.OK);  
    }

Please, let me know of the issues and solution. Also, let me know if the question is not clear. Thanks in advance.

Megha kaur
  • 118
  • 1
  • 13

2 Answers2

1

You can create a filter class by implementing javax.servlet.Filter interface :

@Component
public class YourCORSFilter implements Filter {

    @Override
    public void init(FilterConfig arg0) throws ServletException {}

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletResponse response=(HttpServletResponse) resp;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {}

}

This filter doesn’t do anything right now. I have to configure the Spring application to aware of the filter in web.xml. Just put the following line at the end of web.xml file.

<filter>
    <filter-name>yourCORSFilter</filter-name>
    <filter-class>
        your.package.YourCORSFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>yourCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Now, Spring will put the headers specified in the YourCORSFilter to the response.But you should know that accepting all client origin is not practical and is a really security concern. Allowing only trusted client origin to consume your resources would be more resonable in the real world application.

Abdelghani Roussi
  • 2,707
  • 2
  • 21
  • 39
0

I'm not familiar with Spring, but these are the headers that i set in my PHP-Application:

$headers->addHeaderLine('Access-Control-Allow-Methods', 'GET');
$headers->addHeaderLine('Access-Control-Allow-Credentials', 'true');
$headers->addHeaderLine('Access-Control-Allow-Origin', '*');
$headers->addHeaderLine('Access-Control-Allow-Headers', 'Content-Type, *');

Maybe it helps in your case too :)

regards

bquarta
  • 559
  • 6
  • 19